gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 15:14:51 26 4
gpt4 key购买 nike

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

最佳答案

您需要将子窗口作为 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>

关于javascript - 如何从 Internet Explorer 11 中的 window.open 返回值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50319100/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com