window.addEventListener("message" ... 不支持 IE11

window.addEventListener("message" ... not working with IE11

我正在打开一个弹出窗口,这个弹出窗口向打开的弹出窗口发送了一条 postMessage。 我已经为 'message' 添加了一个 ListenerEvent 到主 window 但这个监听器在 IE 11 中从未被调用,它适用于 firefox。

我已经尝试等待 window,或者用 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);

所以对我来说,结果应该是打开弹出窗口时引发的警报 window。这是 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()。

参考:

HTML5’s window.postMessage API