Search code examples
javascripthtmliframeaddeventlistenerpostmessage

window.addEventListener on a message emitted from an iframe


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?


Solution

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

    window.parent.postMessage(...)