''data' is null or not an object IE8

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 indicates

'data' is null or not an object.

How to fix it?



Solution 1:[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.

Solution 2:[2]

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

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Praveen