Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is html5 postMessage not working for me?

I use a few lines of javascript to create an iframe element, and then I'd like to send it a message, like this:

function loadiframe (callback) {
    var body = document.getElementsByTagName('body')[0];
    var iframe = document.createElement('iframe');
    iframe.id = 'iframe';
    iframe.seamless = 'seamless';
    iframe.src = 'http://localhost:3000/iframe.html';
    body.appendChild(iframe);
    callback();
}

loadiframe(function() {
    cpframe = document.getElementById('iframe').contentWindow;
    cpframe.postMessage('please get this message','http://localhost:3000');
    console.log('posted');
})

And then, inside http://localhost:3000/iframe.html (the source of the iframe) is something like this:

<!DOCTYPE html>
<html>
<head>
<title>does not work</title>
<script>
window.addEventListener("message", receiveMessage, false);
function receiveMessage(event) {
  if (event.origin == "http://localhost:3000") {
    document.write(JSON.stringify(event));
    document.write(typeof event);
  }
}
</script>
</head>
<body>
</body>
</html>

But nothing happens... I even tried to not use the safety check for origin, but even like that nothing happens... Like it never got the message...

Am I in some kind of async problem ? I tried to make sure the iframe was loaded before the postMessage went away...

EDIT1: Also, no errors show on the console...

EDIT2: I tried it in Google Chrome 11 and Firefox 4

Thank you in advance.

like image 924
João Pinto Jerónimo Avatar asked May 17 '11 11:05

João Pinto Jerónimo


1 Answers

There are two possible problems:

  1. You're calling callback before the child frame has loaded - try it in the load event or do it in a setTimeout
  2. I've never managed to get postMessage to work with anything other that '*' as the origin. If I put a URL in there I get a security warning "Security Error: Content at http://xxx/ may not load data from http://yyy/", except only in the error console (Ctrl + Shift + J) not in any other place. I suspect there's some other stuff that needs set up somewhere for that to work, but I've not yet figured out what.

Here's a jsfiddle with a slightly modified version of your code loading a document off my domain, works for me in Firefox and Chrome.

like image 154
robertc Avatar answered Oct 12 '22 11:10

robertc