Two way communication between parent document and iFrame

This page is a simple demonstration of two way communication between iFrame and parent document even if they are hosted in different domains.

index.html

<html>
  <head>
    <style>
      iframe {
      width:50%;
      height:50%;
      }
    </style>

    <script>
      // Listen for iframe loaded event
      window.addEventListener("message", receiveMessage, false);
      function receiveMessage(event)
      {
        if(event.origin !== "http://sandbox.toni-develops.com")
        return
        console.log('[parent]' + event.data);
      }

      function postTheMessage() {
        document.querySelector('#my_iframe').contentWindow.postMessage("Parent doc messaged the iframe", "*");
      }
    </script>
  </head>

  <body>
    <div id="wrapper">
    <iframe id="my_iframe" src="./iframe.html"></iframe>
    <br>
    <button onclick="postTheMessage()">send message to the iframe</button>
    </div>
  </body>
</html>

Two very important notes:
– When we add an event listener, we have to explicitly specify that we are going to listen to a “message” (line 12) and not passing the actual message there.
– we have to declare the event listeners before loading the actual <iframe ..> tag.

 

iframe.html


<html>
<head></head>

<body>
<script>
window.addEventListener("message", receiveMessage, false);

function receiveMessage(event)
{
if(event.origin !== "http://mydev.com")
return
console.log('[iframe]' + event.data);
}

function postTheMessage() {
window.parent.postMessage("iFrame sent a message", "http://mydev.com/sandbox/*");
}

postTheMessage();
</script>

<p>I am an iFrame!</p>
<br>
<button onclick="postTheMessage()">click to post message to the parent document</button>

</body>
</html>

 

How this works:
– Parent document index.html is subscribing for events named “message” (line 12) and calls receiveMessage function (line 13) when the event occur.
– When document is loaded, and the iframe is ready, it emits message to index.html (line 19 in iframe.html)
– When parent document receives message, it makes sure that it comes from the domain that the parent document is interested in, so no other iframe could trigger this action (line 15 in index.html) If so, do something. In this case console.log the message.

 

Leave a Reply