javascript postMessage not working

前端 未结 4 1358
南笙
南笙 2021-02-03 23:19

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

相关标签:
4条回答
  • 2021-02-03 23:54

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

    0 讨论(0)
  • 2021-02-04 00:01

    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>
    
    0 讨论(0)
  • 2021-02-04 00:01

    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);
    
    0 讨论(0)
  • 2021-02-04 00:19

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

    top.postMessage('hello', location.origin);
    
    0 讨论(0)
提交回复
热议问题