首页 > 解决方案 > 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 则不然。不明白为什么。

标签: javascriptinternet-explorer-11addeventlistener

解决方案


尝试使用下面的代码进行测试。它适用于 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()。

参考:

HTML5 的 window.postMessage API


推荐阅读