Send data from parent window to child popup window - PostMessage API

How to communicate between parent window and child popup in JavaScript

Wed, 16 Mar 2022
1 min read

A child enjoying a soft drink on a swing over a river Photo by Jordan Rowland on Unsplash

Post Message API - Sending data from parent window to popup window:

You can use the Post Message API to communicate between parent and child popup windows as well. The only catch is, you’ll need the child window reference in the parent.

Parent

/* Step 1 : Open popup */
const popup = window.open("https://google.com", "_blank");

/* Step 2 : Add message event listener in popup window
Open the console of the newly opened window and add this code */
window.addEventListener("message", function(event) {
  if (typeof(event.data) === "string") {
    alert("Hello from the other side! " + event.data);
  }
});

/* Step 3 : Send a message to popup */
const message = "Hello there!"
popup.postMessage(message, "*");

Parent window to popup communication - Demo