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



为了从使用postMessage发布一些数据的window.open返回一个值,我在父窗口(打开器(中使用了window.addEventListener,并遇到了一个关于回调事件的严重问题,该事件永远不会在 Internet Explorer 11 上执行,并且总是在 Google Chrome 和 Microsoft Edge 上执行。

以下是说明我面临的问题的基本代码:

索引.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>

孩子.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 上的工作代码示例:

索引.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>

儿童.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>

最新更新