Treehouse

window.postMessage Tip: Child-To-Parent Communication

By on  

I wrote a super epic post a few months back about the window.postMessage API that's sweeping the nation.  window.postMessage allows you to send messages not only across frames (regular frame or iframe) but also across domains.  My post showed interaction from parent to child and back to the parent, but didn't detail passing messages from a child to a parent without the parent initializing the conversation.  Let me show you how you can initialize that conversation from child to parent

window.postmessage

The JavaScript

The parent object provides a reference to the main window from the child.  So if I have an iFrame and console the parent within it, the console will read:

// Every two seconds....
setInterval(function() {
	// Send the message "Hello" to the parent window
	// ...if the domain is still "davidwalsh.name"
	parent.postMessage("Hello","http://davidwalsh.name");
},1000);

Since we now have hold of the window, we can postMessage to it:

// Create IE + others compatible event handler
var eventMethod = window.addEventListener ? "addEventListener" : "attachEvent";
var eventer = window[eventMethod];
var messageEvent = eventMethod == "attachEvent" ? "onmessage" : "message";

// Listen to message from child window
eventer(messageEvent,function(e) {
  console.log('parent received message!:  ',e.data);
},false);

The directive above triggers the iFrame to send a message to the parent window every 3 seconds.  No initial message from the main window needed!

ydkjs-1.png

Recent Features

  • Introducing MooTools Templated

    One major problem with creating UI components with the MooTools JavaScript framework is that there isn't a great way of allowing customization of template and ease of node creation. As of today, there are two ways of creating: new Element Madness The first way to create UI-driven...

  • CSS 3D Folding Animation

    Google Plus provides loads of inspiration for front-end developers, especially when it comes to the CSS and JavaScript wonders they create. Last year I duplicated their incredible PhotoStack effect with both MooTools and pure CSS; this time I'm going to duplicate...

Incredible Demos

  • Dijit’s TabContainer Layout:  Easy Tabbed Content

    One of Dojo's major advantages over other JavaScript toolkits is its Dijit library.  Dijit is a UI framework comprised of JavaScript widget classes, CSS files, and HTML templates.  One very useful layout class is the TabContainer.  TabContainer allows you to quickly create a tabbed content...

  • Create a Simple Slideshow Using MooTools

    One excellent way to add dynamism to any website is to implement a slideshow featuring images or sliding content. Of course there are numerous slideshow plugins available but many of them can be overkill if you want to do simple slideshow without controls or events....

Discussion

  1. kevin

    Great article, It worked great on iFrame resizing…WOO HOO! after many failed posts and other methods, this one was so simple.

  2. Stanton W. Jones

    Hey,

    So I’ve scoured the usual forums for a solution to cross-domain iframe communication, and nothing has worked. Not copy/paste, not my own code, not even on the same domain. A lot can change in a year ( haven’t found an article published in 2012 that tells me how to implement this) but I am in deep need of a sanity check.

    –SWJ

  3. Hi,
    My outside of iframe facny box is not working in chrome.so how to solve that problem.

  4. Baker

    Hi David,

    Thanks man. I’ve been looking for a solution for iframe resizing across domains since yesterday. I’ve finally found it.

    Really appreciate it.
    Cheers

  5. karstrasse

    Hi,

    I am getting an error:

    Uncaught TypeError: Object # has no method 'postMessage' even though I am able to get the iframe and its details.

  6. Hey, it looks and works great but on IE, action passed received is undefined.

    parent.postMessage({'action':'RESIZE', 'height':height}, '*');
    

    but here this Action: RESIZE is undefined in postmessage on IE

  7. Abhi

    How do i post the message from iframe which contains https page to a parent page which is http? Even the domains are different? Any idea?

  8. coderone

    It just works :)

  9. Gopinath

    Some browsers supports only ‘string’ message than any other objects(Eg:JSON)

    • Nerudo

      You can simply use

      JSON.stringify(yourJSONObject);
      
  10. john

    Could you do it like this also?

    //the iframe code
    setInterval(function() {
    	parent.postMessage("Hello","http://davidwalsh.name");
    },1000);
    
    //The parent code
    $(window).on('message', function(e){
      console.log('parent received message!:  ',e.data);
    });
    
  11. Pandi

    Hi
    Can postmessage work for HTTPSHTTPS communications?

  12. Mariano

    Thanks, it was very useful and simple.

Wrap your code in <pre class="{language}"></pre> tags, link to a GitHub gist, JSFiddle fiddle, or CodePen pen to embed!