我使用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
。然后我打开任何一个网站,比如https://stackoverflow.com/
。在控制台中,我写了以下代码
window.addEventListener("message", function (event)
{
console.log(event);
})
我观察到没有消息被发送。我忘了什么吗?
window.top.postMessage
将消息发送到当前窗口中的文档,位于任何帧堆栈的顶部。我们把这个叫做a页。
如果页面A的URL出现在浏览器的地址栏中,它将发送一个消息给自己。
如果地址栏中的URL是页面B,它包含一个加载页面A的iframe,那么它将通过帧发送消息到页面B (Stackoverflow没有<iframe src="http://localhost:63342/XXX"></iframe>
,所以这不是你的情况)。
如果你在一个新窗口中加载Page C,那么Page a不会向它发送消息,因为它在一个窗口中。
如果你在同一窗口中从页A导航到页D,那么页A不会向页D发送消息,因为从页A导航会停止JS程序。