javascript postMessage not working

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


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>

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);

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

top.postMessage('hello', location.origin);