簡體   English   中英

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

[英]How to return value from window.open in Internet Explorer 11?

為了從使用postMessage發布一些數據的window.open返回一個值,我在父窗口(opener)中使用了window.addEventListener ,並遇到了一個關於回調事件的嚴重問題,該回調事件永遠不會在Internet Explorer 11上執行並始終執行在谷歌瀏覽器和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>

您需要打開子窗口作為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>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM