27

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

Raynos
  • 156,883
  • 55
  • 337
  • 385
Cystack
  • 3,001
  • 5
  • 31
  • 32

4 Answers4

20

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

Mic
  • 23,536
  • 8
  • 55
  • 69
3

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

top.postMessage('hello', location.origin);
James Lawruk
  • 26,651
  • 19
  • 117
  • 128
3

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>
1

I'm not sure of the security concerns, but typically, I just grab the parent window location like this:

var url = (window.location != window.parent.location) ? document.referrer: document.location;
top.postMessage('message', url);
Phil LaNasa
  • 2,703
  • 1
  • 22
  • 16
  • 1
    The result is that everyone who includes your iframe in his page, will receive the messages. Afaik it's as unsafe as using "*" for the origin. – RiZKiT May 29 '18 at 15:28