I don't know what to do. I tried several sample codes from different sources, I tried them in different browsers (from Chrome 9 to FF 4), and still nothing seems to be working with the "postMessage" function. JS console is giving me nothing, not a single error, still nothing is happening : the frames don't want to communicate. At all. And this isn't even cross-domain : both frames are from my domain.
Here is a sample code from the last try : Parent frame :
<iframe src="IFRAME_URL"></iframe>
<script>
window.addEventListener( "message",
function (e) {
if(e.origin !== 'DOMAIN'){ return; }
alert(e.data);
},
false);
</script>
Child frame :
<html>
<head></head>
<body>
<script>
top.postMessage('hello', 'DOMAIN');
</script>
</body>
Help much appreciated, thanks a lot
postMessage() method safely enables cross-origin communication between Window objects; e.g., between a page and a pop-up that it spawned, or between a page and an iframe embedded within it.
postMessage in your web app sends to the main document's window , not to the iframe's. Specify the iframe's window object: document. getElementById('cross_domain_page').
SendMessage: Sends a message and waits until the procedure which is responsible for the message finishes and returns. PostMessage: Sends a message to the message queue and returns immediately.
The postMessage() function is asynchronous, meaning it will return immediately. So you can not do synchronous communication with it. In your example, the posted message will vanish in the void, because there is no listener for the message event at the time the postMessage() function is executed.
The second parameter of your postMessage
must be an url like http://localhost
If you are not dealing with different origins, entering location.origin
as the targetOrigin will work.
top.postMessage('hello', location.origin);
you can also send the message to any window use top.postMessage('hello', "*");
Html 1:
<iframe src="IFRAME_URL"></iframe>
<script>
window.addEventListener( "message",
function (e) {
alert(e.data);
},
false);
</script>
html 2:
<html>
<head></head>
<body>
<script>
top.postMessage('hello', '*');
</script>
</body>
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