window.addEventListener 从 iframe 发出的消息

window.addEventListener on a message emitted from an iframe

我有两个 html 文件。第一个称为 post.html,它在 window 上注册一个事件侦听器并向 window:

发送消息
<html>
    <head>
        <script>
            window.addEventListener("message", function(event) {
                console.log("found event in post!", event)
            }); 
            window.postMessage({
               'data': ["some data"]
            },"*");   
        </script>
    </head>
    <body>
    </body>
</html>

我有另一个名为 listner.html 的 html 文件,它只监听来自 window 的消息并将 post.html 作为 iframe 加载:

<html>
    <head>
        <script>
            window.addEventListener("message", function(event) {
              console.log("event found in listen!", event)
            }); 
        </script>
    </head>
    <body>
        <iframe src="post.html"></iframe>
    </body>
</html>

如果我加载 listener.html,我得到的日志表明 post.html 中的事件侦听器检测到发布到 post.html 中的 window 的消息,但我没有无法从 listener.html 获取任何日志。我的理解是我应该能够通过两个文件之间的 window 对象进行通信,并且 listener.html 中的事件侦听器应该接收事件。知道为什么这不起作用吗?

post.html 将消息发布到它自己的 window,而不是包含 listener.html

的 window
window.parent.postMessage(...)