Categories
JavaScript Answers

How to use window.postMessage across domains with JavaScript?

Spread the love

Sometimes, we want to use window.postMessage across domains with JavaScript.

In this article, we’ll look at how to use window.postMessage across domains with JavaScript.

How to use window.postMessage across domains with JavaScript?

To use window.postMessage across domains with JavaScript, we call top.postMessage in our iframe.

For instance, we write

top.postMessage("hello", "A");

in our iframe to call postMessage to send data to the parent page.

Then we write

window.addEventListener(
  "message",
  (e) => {
    if (e.origin !== "B") {
      return;
    }
    alert(e.data);
  },
  false
);

in our parent page to listen for the message event.

In the callback, we check the domain the event is originated from with e.origin.

And we get the arguments passed into postMessage with e.data.

Conclusion

To use window.postMessage across domains with JavaScript, we call top.postMessage in our iframe.

Leave a Reply

Your email address will not be published.

If you like the content of this blog, subscribe to my email list to get exclusive articles not available to anyone else.