javascript - window.addEventListener("message" ... 不适用于 IE11
问题描述
我正在打开一个弹出窗口,这个弹出窗口向开启者发送了一个 postMessage。我已在“消息”的主窗口中添加了一个 ListenerEvent,但在 IE 11 中从未调用此侦听器,它适用于 firefox。
我已经尝试等待窗口,或者用 setInterval 替换 eventListener 的技巧,但在这种情况下我无法访问事件的数据。我已经检查了所有与我的问题相似的线程。所以我只是尝试一个小而简单的例子来检查 addEventListener 'message' 是否与 IE11 一起工作,但它没有。
我的主 html 页面中的脚本:
var popup = window.open("popup.html", "Connection",
'toolbar=no, location=no, directories=no, menubar=no, status=yes, scrollbars=no, resizable=yes, copyhistory=no, '
+ 'width=' + w + ', height=' + h + ', top=' + y + ', left=' + x);
popup.postMessage("The user is 'bob' and the password is 'secret'",
"*");
},500);
我的弹出 html 页面中的脚本:
function receiveMessage(event)
{
alert("OK popup");
console.log("djedjeidjeidjiejdie");
}
window.addEventListener("message", receiveMessage, false);
所以对我来说,结果应该是打开弹出窗口时出现的警报窗口。Firefox 是这种情况,但 IE11 则不然。不明白为什么。
解决方案
尝试使用下面的代码进行测试。它适用于 IE 11。
主页代码:
<html>
<head>
<title>Page Title</title>
<script>
//create popup window
var domain = 'http://example.com';
var myPopup = window.open(domain + '/HTML/popup_page.html','myWindow');
//periodical message sender
setInterval(function(){
var message = 'Hello! The time is: ' + (new Date().getTime());
console.log('blog.local: sending message: ' + message);
myPopup.postMessage(message,domain); //send the message and target URI
},6000);
//listen to holla back
window.addEventListener('message',function(event) {
if(event.origin !== 'http://example.com') return;
console.log('received response: ',event.data);
},false);
</script>
</head>
<body>
<h1>Main page</h1>
</body>
</html>
弹出页面代码:
<!Doctype html>
<html>
<head>
<script>
window.addEventListener('message',function(event) {
if (event.origin !== 'http://example.com') return;
alert("OK popup");
console.log('message received: ' + event.data,event);
event.source.postMessage('holla back youngin!',event.origin);
},false);
</script>
</head>
<body>
<h1>popup_page</h1>
</body>
</html>
IE中的输出:
请注意,在运行代码时,您还会收到一个 alert()。
参考:
推荐阅读
- apache - httpd: (13)Permission denied: AH00072: make_sock: could not bind to address [::]:5000
- c# - 扩展 Web 服务中的 Acumatica PR203000 - 系统未能提交 EmployeeAttributes 行
- blogger - 如何在不同的博客页面上显示相同的 Disqus 线程?
- flutter - 错误:此库已禁用空安全功能
- javascript - 为什么我在 Bootstrap 中的轮播指示器不起作用?
- matlab - 在 MATLAB 中绘制傅里叶级数的直流分量
- java - 将此多播路由(在 Apache-camel 中)从核心 spring 转换为 spring boot 时出错
- javascript - 根据拖动动量 Javascript 找出函数应该被调用的频率
- html - 在引导程序 4 中调整 col 内的跨度值
- powershell - 有人可以帮助正确添加电子邮件功能吗