Search code examples
javascriptpostmessage

Postmessage not working


I would like to send message from one domain to another. For this purpose am using postMessage. I have a code which seems to be good but still it is not able to send message. Have gone through various related post but no use.

Even on same domain it is not working.

It would be very helpful if anyone could point out what's wrong with code. Thanks

Main Page:

<html>
<head></head>
<body>
    <iframe src="http://localhost/sandbox/test/test2.html"></iframe>
    <script>
        window.addEventListener( "message",
          function (e) {
                if(e.origin !== 'http://localhost/sandbox/test/test2.html'){ return; } 
                alert(e.data);
          },
          false);
    </script>
</body>
</html>

Iframe content:

<html>
    <head></head>
    <body>
        <script>
            top.postMessage('hello', 'http://localhost/sandbox/test/test.html');
        </script>
    </body>
</html>

Solution

  • You should do some basic debugging to find out where the problem is.

    Your function starts with an if test, but you don't seem to have determined if the problem is that the if isn't being entered or if the function isn't being called at all.

    Put a console.log() statement in there to find out.

    Test what the value of e.origin is.

    You should find that it is http://localhost (which doesn't match what you are testing for). Origins do not include the path segement.

    That is why your test is failing.