addEventListener在firefox和chrome中不起作用

时间:2013-12-13 03:28:13

标签: javascript google-chrome firefox

我使用postMessage函数向我的页面中的iframe发送消息,如此

$(document).ready(function(){
    document.getElementById('test').contentWindow.postMessage(message, '*');
)};//test is the id of my iframe in a.html

在b.html中,我使用window.addEventListener('message', onmessage, false);来接收此消息:

window.onload = function() { 
    var onmessage = function(e) { 
        document.getElementById('display').innerHTML = e.data; 
    }; 
    window.addEventListener('message', onmessage, false); 
}; //this is the javascript in b.html

IE10中效果很好,但我无法在chromefirefox收到任何消息!为什么?

3 个答案:

答案 0 :(得分:0)

如果浏览器是最新的,请检查您的Chrome和FireFox更新。

OR

...试

 alert(onmessage);

如果他们的任何消息输出。

答案 1 :(得分:0)

不要将你的代码放在window.onload中,也许当你调用postMessage时,iframe onload还没有被触发

 var onmessage = function(e) { 
        console.log(e);
    };
if ( typeof window.addEventListener != 'undefined') {
            window.addEventListener('message', onmessage, false);
          } else if ( typeof window.attachEvent != 'undefined') {
            window.attachEvent('onmessage', onmessage);
          }

答案 2 :(得分:0)

$(document).ready将在DOMContentLoaded上运行,这可能在子帧完成加载之前发生。因此,在您在孩子中添加听众之前,很有可能在父母中发送消息。

相关问题