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

时间:2018-05-13 18:05:50

标签: javascript callback

为了从使用window.open发布一些数据的postMessage返回一个值,我在父窗口(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 个答案:

答案 0 :(得分:1)

您需要以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>