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.
console.log
is not supported in older version of IEs. Try removing the lineIE8 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:
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 thewindow
object). So on IE8 and earlier,e
will beundefined
, whereas on IE9+ and all other browsers,e
will be the event object.So this line:
...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." Sinceundefined
is falsey, on IE8 and earlier,e = e || window.event
assignswindow.event
toe
. On IE9+ and all other browsers, it just assignse
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.