为什么html5 postMessage对我不起作用?

| 我使用几行JavaScript创建iframe元素,然后向其发送一条消息,如下所示:
function loadiframe (callback) {
    var body = document.getElementsByTagName(\'body\')[0];
    var iframe = document.createElement(\'iframe\');
    iframe.id = \'iframe\';
    iframe.seamless = \'seamless\';
    iframe.src = \'http://localhost:3000/iframe.html\';
    body.appendChild(iframe);
    callback();
}

loadiframe(function() {
    cpframe = document.getElementById(\'iframe\').contentWindow;
    cpframe.postMessage(\'please get this message\',\'http://localhost:3000\');
    console.log(\'posted\');
})
然后,在http:// localhost:3000 / iframe.html(iframe的源)内部是这样的:
<!DOCTYPE html>
<html>
<head>
<title>does not work</title>
<script>
window.addEventListener(\"message\", receiveMessage, false);
function receiveMessage(event) {
  if (event.origin == \"http://localhost:3000\") {
    document.write(JSON.stringify(event));
    document.write(typeof event);
  }
}
</script>
</head>
<body>
</body>
</html>
但是什么也没发生...我什至试图不使用安全性检查作为原产地,但是即使那样什么也没有发生...就像它永远都没有得到消息... 我是否遇到某种异步问题?我试图确保在postMessage消失之前已加载iframe ... EDIT1:另外,控制台上没有错误显示... EDIT2:我在Google Chrome 11和Firefox 4中尝试过 先感谢您。     
已邀请:
有两个可能的问题: 您要在子框架加载之前致电
callback
-在
load
事件中尝试或在
setTimeout
中进行 我从来没有设法使ѭ5与其他以“ *”为源的东西一起工作。如果我在其中放置U​​RL,则会收到安全警告\“安全错误:http:// xxx /上的内容可能无法从http:// yyy / \加载数据”,只有在错误控制台中才能这样做(Ctrl + Shift + J)不在任何其他地方。我怀疑还有一些其他的东西需要在某个地方设置才能起作用,但是我还没有弄清楚是什么。 这是一个jsfiddle,其代码的经过稍微修改的版本从我的域中加载了文档,并在Firefox和Chrome中对我有效。     

要回复问题请先登录注册