Skip to content

Instantly share code, notes, and snippets.

@vishaltelangre
Last active March 24, 2022 04:47
Show Gist options
  • Save vishaltelangre/7542832 to your computer and use it in GitHub Desktop.
Save vishaltelangre/7542832 to your computer and use it in GitHub Desktop.
window.postMessage example
// recieve message
// event object contains:
// - data: message sent
// - origin (host from which the message was sent, e.g. http://blah.example.com)
// - source (reference to a Window object from which message was sent)
function postMessageHandler( event ) {
console.log("We've got a message!");
console.log("* Message:", event.data);
console.log("* Origin:", event.origin);
console.log("* Source:", event.source);
// check request is from legitimate source and message is expected or not
if ( event.origin !== 'http://blah.example.com' ) { return; }
if ( event.data === 'Hello' ) {
// give response
event.source.postMessage( 'world!', 'http://blah.example.com' );
}
}
if (window.addEventListener) {
window.addEventListener("message", postMessageHandler, false);
} else {
window.attachEvent("onmessage", postMessageHandler);
}
// send message to a window object
// postMessage(message, window origin)
// - message: any object, viz. string, JSON, array, Regex, ImageFile, Blob, etc.
window.postMessage("Hello", "http://blah.example.com");
// Sample Output
/*
We've got a message!
* Message: Hello
* Origin: http://blah.example.com
* Source:
Window
*/
  • Legacy browser such as IE6, IE7 doesn't support window.postMessage

    • Fallbacks: window.name, using URL fragment identifier (or hash), using an Adobe Flash object
    • This techniques skips SOP checks, somehow
  • easXDM is for enhanced fallback support

  • window.message technique

    • open iframe within in the doucment, which has cross-domain src, set window.name property with desired message, and redirect it to parent document's origin's page -- so now the iframe hosts a document on the same domain of parent document, and still contains the value of window.name which was set earlier.
    // in document on publisher's domain (where we're listening for a message)
    // create iframe
    var iframe = document.createElement('iframe');
    var body = document.getElementsByTagName('body')[0];
    
    iframe.style.display = 'none';
    iframe.src = 'http://3rdpartyserver.com/nametransport/server.html'; // remote iframe page url
    
    var done = false;
    // event handler fires when iframe loads new document
    iframe.onreadystatechange = function () {
      if (iframe.readyState !== 'complete' || done) {
        return;
      }
      
      console.log('Listening');
      
      var name = iframe.contentWindow.name; // window.name returns undefined if inaccessible
      if (name) {
        console.log('Data: ' + iframe.contentWindow.name);
        done = true;
      }
    };
    
    body.appendChild(iframe);
    <!-- in iframe, we set window.name and redirect to parent window's
        domain object by setting location to empty.html page on publisher's site
    -->
    <!DOCTYPE html>
    <html>
      <head>
        <script>
          function init() {
            window.name = 'Hello world!';
            window.location = 'http://publisher.com/empty.html';
          }
        </script>
      </head>
      <body onload="init();"></body>
    </html>
    • this is bad, it's uncertain that publisher might host empty.html or we've to redirect to random 404 page, but it will unnecessarily increase traffic on publisher's site by doing like so. But in easyXDM, such static empty.html page is forcefully cached and overcome this issue.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment