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.
There are two possible problems:
callback
before the child frame has loaded - try it in the load
event or do it in a setTimeout
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With