简体   繁体   中英

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?

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

OR

try....

 alert(onmessage);

if their any message output.

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

$(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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM