Skip to content
Backwards compatible window.postMessage()
JavaScript
Latest commit 82edb7b Jun 3, 2013 @joshfraser update readme
Failed to load latest commit information.
README.md update readme Jun 3, 2013
child.html initial commit Jun 3, 2013
parent.html initial commit Jun 3, 2013
postmessage.js initial commit Jun 3, 2013

README.md

postmessage

Backwards compatible window.postMessage()

Demo

See an example of this library in action or read a post on my blog about how it works.

Usage

There are two parts to using this code: posting and listening. Both are relatively simple. To post a message we call XD.postMessage with a message, a URL and the frame that we want to talk to. Notice that we start off by passing the URL of the parent page to the child frame. This is important so the child knows how to talk back to the parent.

// pass the URL of the current parent page to the iframe using location.hash
src = 'http://joshfraser.com/code/postmessage/child.html#' + encodeURIComponent(document.location.href);
document.getElementById("xd_frame").src = src;

function send(msg) {
    XD.postMessage(msg, src, frames[0]);
    return false;
}

Setting up the listener on the child is also easy to do:

var parent_url = decodeURIComponent(document.location.hash.replace(/^#/, ''));

XD.receiveMessage(function(message){
    window.alert(message.data + " received on "+window.location.host);
}, 'http://onlineaspect.com');

Credits & license:

Something went wrong with that request. Please try again.