window.attachEvent似乎在IE8中不起作用

dsp*_*099 2 javascript javascript-events internet-explorer-8

首页:

...
<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>
Run Code Online (Sandbox Code Playgroud)

page2.html:

<script>
var message = "hello!";
parent.postMessage(message, '*');
</script>
Run Code Online (Sandbox Code Playgroud)

此代码在Chrome,FF和Opera中运行良好.当然,IE有自己的做事方式,所以尽管使用了自己的代码,这些代码仍无法正常工作.attachEvent.

page2.html实际上是另一个域的页面; 我正在发送正确的P3P标头(应该没关系,但就是这样).

我如何找出为什么postMessage似乎没有到达父页面?

Nie*_*sol 11

attachEvent在表单中获取其事件名称"onmessage",而不是addEventListener(使用"message")

  • ...它使用`window.event`而不是`event`参数. (3认同)