window.addEventListener on a message emitted from an iframe

不问归期 提交于 2021-02-11 14:02:27

问题


I have two html files. The first is called post.html and it registers an event listener on the window and posts a message to the 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>

I have a second html file called listner.html that just listens for a message from the window and loads post.html as an 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>

If I load listener.html, I get the log indicating that the event listener in post.html detected the message posted to the window in post.html but I don't get any log from listener.html. My understanding was that I should be able to communicate via the window object between the two files and the event listener in listener.html should receive the event. Any idea why this isn't working?


回答1:


post.html is posting the message to its own window, and not to the window containing listener.html

window.parent.postMessage(...)


来源:https://stackoverflow.com/questions/54519710/window-addeventlistener-on-a-message-emitted-from-an-iframe

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!