我使用WebStorm 2022.1运行一个HTML文件
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Window.postMessage</title>
</head>
<body>
<script>
let time = 0;
setInterval
(
function ()
{
window.top.postMessage("Source01", "*");
console.log(`Time: ${++time}`);
},
2000,
time
)
</script>
</body>
</html>在地址:http://localhost:63342/XXX .Then我打开任何网站,比如说https://stackoverflow.com/ .In控制台,我写了以下代码
window.addEventListener("message", function (event)
{
console.log(event);
})我注意到没有发送任何信息。我是不是忘了什么?
发布于 2022-05-23 08:28:24
window.top.postMessage将消息发送到当前窗口中的任何帧堆栈顶部的文档。我们叫这页A吧。
如果页面A的URL出现在浏览器的地址栏中,它将向自己发送一条消息。
如果地址栏中的URL是Page,并且包含一个加载A页的iframe,那么它将通过框架将消息发送到B页(Stackoverflow没有<iframe src="http://localhost:63342/XXX"></iframe>,所以这不是您的情况)。
如果您在一个新窗口中加载Page,那么Page将不会向它发送消息,因为它位于一个窗口中。
如果您在同一个窗口中从A页导航到D页,那么A页将不会向Page发送消息,因为从页面A导航将停止JS程序。
https://stackoverflow.com/questions/72345377
复制相似问题