Skip to content

Instantly share code, notes, and snippets.

@benjamine
Created June 7, 2011 15:04
Show Gist options
  • Save benjamine/1012435 to your computer and use it in GitHub Desktop.
Save benjamine/1012435 to your computer and use it in GitHub Desktop.
window.postMessage

The following Javascript snippet test the support for the window.postMessage function. This function allows to send data through different browser windows or frames (including iframes) in a safe cross-domain manner. Modern browser are blocking other type of communication between cross-domain window/frames so this will soon be the only way to do this.

this.testData = {
message: 'a random message '+Math.floor(Math.random()*10000),
log: []
};
// test that postMessage is supported
ok(typeof window.postMessage == 'function', 'window.postMessage is supported');
// test posting a message to the same frame
stop();
var d = this.testData;
window.addEventListener("message", function (e) {
if (e.source !== this) {
return; // unsafe message
}
d.log.unshift(e.data);
});
window.postMessage(d.message, '*');
setTimeout(function(){
equals(d.log[0], d.message, 'message got logged');
start();
}, 200);
// test posting a message to an iframe
stop(1000);
var $iframe = $('<iframe/>').hide().appendTo('body'),
doc = $iframe[0].contentDocument;
window.addEventListener("message", function (e) {
if (e.source === $iframe[0].contentWindow) {
equals(e.data, 'RE:hello!','received iframe response message');
start();
}
});
// prepare parrot iframe
doc.write('<body><script type="text/javascript"'+'>\n'+
' window.addEventListener("message", function (e) {\n'+
' setTimeout(function(){ e.source.postMessage("RE:"+e.data,"*"); },50);\n'+
' });\n'+
'</'+'script></body>');
// send message to parrot iframe
$iframe[0].contentWindow.postMessage('hello!','*');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment