Cross-Window Messaging

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

Scripts on different pages are only allowed to access each 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 !== "")  

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+" ";
document.getElementById("send").onclick = function(){
    var msg = document.getElementById("res").innerHTML;
    frame.postMessage(msg, "");

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

Share this