Is cross-origin postMessage broken in IE10?

后端 未结 8 2124
星月不相逢
星月不相逢 2020-11-27 11:06

I\'m trying to make a trivial postMessage example work...

  • in IE10
  • between windows/tabs (vs. iframes)
  • across origins

相关标签:
8条回答
  • 2020-11-27 11:48

    MessageChannel doesn't work for IE 9-11 between windows/tabs since it relies on postMessage, which is still broken in this scenario. The "best" workaround is to call a function through window.opener (ie. window.opener.somefunction("somedata") ).

    Workaround in more detail here

    0 讨论(0)
  • 2020-11-27 11:49

    Building upon the answers by LyphTEC and Akrikos, another work-around is to create an <iframe> within a blank popup window, which avoids the need for a separate proxy page, since the blank popup has the same origin as its opener.

    Launcher page at http://example.com/launcher.htm

    <html>
      <head>
        <title>postMessage launcher</title>
        <script>
          function openWnd() {
            var w = window.open("", "theWnd", "resizeable,status,width=400,height=300"),
                i = w.document.createElement("iframe");
    
            i.src = "http://example.net/remote.htm";
            w.document.body.appendChild(i);
    
            w.addEventListener("message", function (e) {
              console.log("message from " + e.origin + ": " + e.data);
    
              // Send a message back to the source
              e.source.postMessage("reply", e.origin);
            });
          }
        </script>
      </head>
      <body>
        <h2>postMessage launcher</h2>
        <p><a href="javascript:openWnd();">click me</a></p>
      </body>
    </html>
    

    Remote page at http://example.net/remote.htm

    <html>
      <head>
        <title>postMessage remote</title>
        <script>
          window.addEventListener("message", function (e) {
            alert("message from " + e.origin + ": " + e.data);
          });
    
          // Send a message to the parent window every 5 seconds
          setInterval(function () {
            window.parent.postMessage("hello", "*");
          }, 5000);
        </script>
      </head>
      <body>
        <h2>postMessage remote</h2>
      </body>
    </html>
    

    I'm not sure how fragile this is, but it is working in IE 11 and Firefox 40.0.3.

    0 讨论(0)
提交回复
热议问题