[英]How to return value from window.open in Internet Explorer 11?
In order to return a value from window.open
which uses postMessage
to post some data, I used window.addEventListener
in parent window (opener) and faced a serious issue regarding the callback event, which never gets executed on Internet Explorer 11 and always executes on Google Chrome and Microsoft Edge. 为了从使用
postMessage
发布一些数据的window.open
返回一个值,我在父窗口(opener)中使用了window.addEventListener
,并遇到了一个关于回调事件的严重问题,该回调事件永远不会在Internet Explorer 11上执行并始终执行在谷歌浏览器和Microsoft Edge上。
Below is the basic code to illustrate the problem I'm facing: 下面是说明我面临的问题的基本代码:
index.html 的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 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>
Use the window.parent.postMessage("message", "*");
使用
window.parent.postMessage("message", "*");
in child window to post the message to parent window, and the parent needs to listen to the event using window.onmessage
. 在子窗口中将消息发布到父窗口,父节点需要使用
window.onmessage
监听事件。
Below is the working code example on Internet Explorer: 下面是Internet Explorer上的工作代码示例:
index.html: 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: 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.