How do you use window.postMessage across domains?
Here is an example that works on Chrome 5.0.375.125.
The page B (iframe content):
<html> <head></head> <body> <script> top.postMessage('hello', 'A'); </script> </body></html>
Note the use of top.postMessage
or parent.postMessage
not window.postMessage
here
The page A:
<html><head></head><body> <iframe src="B"></iframe> <script> window.addEventListener( "message", function (e) { if(e.origin !== 'B'){ return; } alert(e.data); }, false); </script></body></html>
A and B must be something like http://domain.com
EDIT:
From another question, it looks the domains(A and B here) must have a /
for the postMessage
to work properly.
You should post a message from frame to parent, after loaded.
frame script:
$(document).ready(function() { window.parent.postMessage("I'm loaded", "*");});
And listen it in parent:
function listenMessage(msg) { alert(msg);}if (window.addEventListener) { window.addEventListener("message", listenMessage, false);} else { window.attachEvent("onmessage", listenMessage);}
Use this link for more info: http://en.wikipedia.org/wiki/Web_Messaging
Probably you try to send your data from mydomain.com to www.mydomain.com or reverse, NOTE you missed "www". http://mydomain.com and http://www.mydomain.com are different domains to javascript.