'data' is null or not an object IE8

╄→гoц情女王★ 提交于 2019-12-14 03:57:34

问题


I am transmitting message from an iframe to its parent page using postMessage. This is my code. In iframe:

$(".history_date").click(function(event) {
  window.top.postMessage($(this).text(), "*");
});

In parent page:

$(function(){
window.onmessage = function(e){
    if(e.data){
        //do something

    }
};
});

It works well in chrome, firefox and IE9/10, but in IE8, the error indecates

'data' is null or not an object.

How to fix it? Thanks in advance.


回答1:


IE8 still lacks DOM2 event attachment, still using the global event object rather than one it passes into event handlers. You've said the error is 'data' is null or not an object, are you sure it's not 'e' is null or not an object?

If it is, then this should fix it:

window.onmessage = function(e){
   e = e || window.event;
   if (e.data) {
       // ...
   }
};

On IE8 and earlier, no argument is passed into event handlers. Instead, you look at the global event variable (global variables are also properties of the window object). So on IE8 and earlier, e will be undefined, whereas on IE9+ and all other browsers, e will be the event object.

So this line:

e = e || window.event;

...uses the curiously-powerful || operator, which will return its first argument if that argument is "truthy," or its second argument if the first is "falsey." Since undefined is falsey, on IE8 and earlier, e = e || window.event assigns window.event to e. On IE9+ and all other browsers, it just assigns e back to itself (a no-op).

This is a common pattern in code that has to interact with both IE8 and earlier and browsers that pass the event object into the handler.




回答2:


console.log is not supported in older version of IEs. Try removing the line

console.log("message get: "+ e.data);


来源:https://stackoverflow.com/questions/17609468/data-is-null-or-not-an-object-ie8

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!