如何在Internet Explorer 11中从window.open返回值?

4
为了从使用postMessage来传递一些数据的window.open中返回一个值,我在父窗口(opener)中使用window.addEventListener,并遇到了一个严重的问题,即回调事件在Internet Explorer 11上永远不会被执行,而在Google Chrome和Microsoft Edge上总是会被执行。
以下是基本代码,用于说明我面临的问题: index.html
<!DOCTYPE html>
<html>
   <head>
      <meta charset="UTF-8" />
      <meta http-equiv="X-UA-Compatible" content="IE=edge" />
      <!--  <meta http-equiv="X-UA-Compatible" content="IE=8;IE=9;IE=10;IE=11;IE=edge"> -->
      <!-- <script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
         crossorigin="anonymous"></script> -->
   </head>
   <body>
      <p>Click the button to open a new browser window.</p>
      <p id="message"></p>
      <button onclick="myFunction()">Try it</button>
      <script>
         var messageEle = document.getElementById('message');
         function receiveMessage(e) {
             messageEle.innerHTML = "Message Received: " + e.data;
         }
         window.addEventListener('message', receiveMessage, false);
         function myFunction() {
             window.open("child.html", "test", "top=500,left=500,width=400,height=400");
         }
      </script>
   </body>
</html>

child.html

<!DOCTYPE html>
<html>
   <body>
      <p>Child Window</p>
      <a href="javascript:;" onclick="sendMessage()">Send Message</a>
      <script>
         function sendMessage(){
             window.opener.postMessage("test", "*");
             window.close();
         }

      </script>
   </body>
</html>
1个回答

2

您需要将子窗口作为iFrame打开!

在子窗口中使用window.parent.postMessage("message", "*");向父窗口发布消息,而父窗口需要使用window.onmessage来监听事件。

以下是Internet Explorer上的工作代码示例:

index.html:

<!DOCTYPE html>
<html>
   <head>
      <meta charset="UTF-8" />
      <meta http-equiv="X-UA-Compatible" content="IE=edge" />
   </head>
   <body>
      <h1>Parent Window</h1>
      <p>Click the button to open a new browser window.</p>
      <h3 id="message"></h3>
      <iframe src="child.html" width="500" height="500"></iframe>
      <script>
         window.onmessage = function (e) {
          var messageEle = document.getElementById('message');
              messageEle.innerHTML = "Message Received from child window: " + e.data;
         };
      </script>
   </body>
</html>

child.html:

<!DOCTYPE html>
<html>
   <body>
      <h1>Child Window</h1>
      <a href="javascript:;" onclick="sendMessage()">Send Message to parent window</a>
      <script>
         function sendMessage(){
             window.parent.postMessage("Hello", "*");
             window.close();
         }
      </script>
   </body>
</html>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接