derekxyz
derekxyz

Reputation: 23

addEventListener is not working in firefox and chrome

i use the postMessage function to send a message to a iframe in my page like this

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

and in b.html,i use window.addEventListener('message', onmessage, false);to receiver this message:

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

it works well in IE10,but i can't receive any message in chrome and firefox!why?

Upvotes: 2

Views: 4705

Answers (3)

Boris Zbarsky
Boris Zbarsky

Reputation: 35074

$(document).ready will run on DOMContentLoaded, which can happen before the subframe is done loading. So there is a good chance you're sending the message in the parent before you've added the listener in the child.

Upvotes: 0

yoyo
yoyo

Reputation: 722

Don't put your code in window.onload ,maybe when you call postMessage,iframe onload has not been triggered

 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);
          }

Upvotes: 1

Marc
Marc

Reputation: 139

Check your Chrome and FireFox Update if the browser are latest.

OR

try....

 alert(onmessage);

if their any message output.

Upvotes: 0

Related Questions