window.attachEvent没有'我似乎在IE8工作

window.attachEvent doesn't seem to be working in IE8

本文关键字:IE8 工作 attachEvent 没有 window      更新时间:2023-09-26

首页:

...
<script>
if (window.addEventListener) {
 // addEventListener equivalent of code below
} else if (window.attachEvent) {
 window.attachEvent("message", function(e) {
  if (e.origin != "page2.html") { return; }
  alert(e.data);
 });
}
</script>
<iframe src="page2.html"></iframe>

page2.html:

<script>
var message = "hello!";
parent.postMessage(message, '*');
</script>

此代码在Chrome、Firefox和Opera中运行良好。当然,IE有自己的做事方式,所以尽管使用了自己的.attachEvent,但这段代码还是不起作用。

page2.html实际上是另一个域上的一个页面;我正在发送正确的P3P标头(应该不重要,但确实如此)。

如何找出postMessage似乎没有到达父页的原因?

attachEvent的事件名称的形式为"onmessage",而不是addEventListener(使用"message"