Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript postMessage not working

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

like image 914
Cystack Avatar asked Jun 20 '11 13:06

Cystack


People also ask

What is postMessage in Javascript?

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.

How do you send iframe to postMessage?

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').

What is the difference between SendMessage and postMessage?

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.

Is postMessage asynchronous?

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.


3 Answers

The second parameter of your postMessage must be an url like http://localhost

like image 67
Mic Avatar answered Oct 07 '22 03:10

Mic


If you are not dealing with different origins, entering location.origin as the targetOrigin will work.

top.postMessage('hello', location.origin);
like image 3
James Lawruk Avatar answered Oct 07 '22 03:10

James Lawruk


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>
like image 3
user10946822 Avatar answered Oct 07 '22 03:10

user10946822