Send data between parent window and child iframe - PostMessage API

How to communicate between parent window and child or iframe in JavaScript

Tue, 15 Mar 2022
2 min read

Send data from one context to another

With JavaScript, you can send data from one context to another. If your main window opens up a new tab, you can send data from the main window to the new tab and vice versa using the postMessage() and Channel Messaging API. In this post, we’ll only talk about the postMessage API.

Let’s get real - some examples of communication between contexts and a list of all the possible contexts

1. Sending data from parent window to child iframe:

Let’s see how we can send some data from the parent window to the child iframe.

Parent

<div id="app">
  <input id="message" type="text" />
  <button id="sendMessage">Send Message</button>
</div>
<script>
  var button = document.querySelector("#sendMessage");

  function sendMessage() {
    const message = document.querySelector("#message").value;
    const iframe = document.querySelector("iframe");
    iframe.contentWindow.postMessage(message, "*");
  }

  button.addEventListener("click", sendMessage);
</script>

<iframe src="page2.html"></iframe>

Iframe (page2.html)

<script>
  window.addEventListener('message', function(event) {
    console.log("Message received from the parent: " + event.data); // Message received from parent
  });
</script>

And that’s it! We’ve sent a message from the parent window to the child iframe. You can fire up your console and see the messages for yourself. Or you could always have a look at the demo below.


2. Sending data from child iframe to parent window:

Sending some data from the child iframe to the parent window is also pretty simple. Whenever you embed an iframe, the iframe will have a reference to the parent window. You just need to use the PostMessage API to send data via the window.parent reference of the parent window.

Parent

<script>
  window.addEventListener('message', function(event) {
    console.log("Message received from the child: " + event.data); // Message received from child
  });
</script>

Child iframe code - page2.html

<input type="text" id="messageText" />
<button id="sendMessage">Send Message to Parent</button>
<script>
  var button = document.querySelector("#sendMessage");
  button.addEventListener("click", function () {
    var message = document.querySelector("#messageText").value;
    // Send `message` to the parent using the postMessage method on the window.parent reference.
    window.parent.postMessage(message, "*");
  });
</script>

Demo - Send data to and from the child iframe