Hemanth's Scribes

javascript

Cross-Window Messaging

Author Photo

Hemanth HM

Thumbnail

Cross-origin/window communication is possible with the HTML5 API window.postMessage.

Scripts on different pages are only allowed to access each other only if the pages which executed them are at locations with the same protocol and host, but window.postMessage provides a controlled mechanism to circumvent this restriction in a way which is secure when properly used.

Before diving into some theory, have a look at the demo

The MessageEvent interface is as below:

interface MessageEvent : Event {
  readonly attribute any data;
  readonly attribute DOMString origin;
  readonly attribute DOMString lastEventId;
  readonly attribute WindowProxy source;
  readonly attribute MessagePortArray ports;
  void initMessageEvent(
    in DOMString typeArg, 
    in boolean canBubbleArg, 
    in boolean cancelableArg, 
    in any dataArg, 
    in DOMString originArg, 
    in DOMString lastEventIdArg, 
    in WindowProxy sourceArg, 
    in MessagePortArray portsArg
  );
};

data and origin are of the prime most importance here - the data gives the message that is sent via postMessage and origin gives the domain origin.

One can easily check and return if the event origin is not as expected:

if (event.origin !== "http://h3manth.com") {
    return;
}

If you check out the source of the demo:

var frame = document.getElementById("if").contentWindow;
frame.onmessage = function(e) {
    frame.document.body.innerHTML += "Message from " + e.origin + " " + e.data;
};

document.getElementById("send").onclick = function() {
    var msg = document.getElementById("res").innerHTML;
    frame.postMessage(msg, "http://h3manth.com/blog");
};

Notice that postMessage is not from the same page as the demo is in.

#javascript#html5
Author Photo

About Hemanth HM

Hemanth HM is a Sr. Machine Learning Manager at PayPal, Google Developer Expert, TC39 delegate, FOSS advocate, and community leader with a passion for programming, AI, and open-source contributions.