相关疑难解决方法(0)

为什么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');
})
Run Code Online (Sandbox Code Playgroud)

然后,在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>
Run Code Online (Sandbox Code Playgroud)

但没有任何反应......我甚至试图不使用原产地的安全检查,但即使没有发生任何事情......就像从来没有得到消息......

我在某种异常问题吗?我试图确保在postMessage消失之前加载了iframe ...

EDIT1:此外,控制台上没有显示错误......

EDIT2:我在Google Chrome 11和Firefox 4中尝试过它

先感谢您.

html5 postmessage

5
推荐指数
1
解决办法
1万
查看次数

标签 统计

html5 ×1

postmessage ×1