为什么html5 postMessage不能为我工作?

前端之家收集整理的这篇文章主要介绍了为什么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中尝试过它

先感谢您.

解决方法

有两个可能的问题:

>您正在加载子帧之前调用回调 – 在load事件中尝试它或在setTimeout中执行它
>我从来没有设法让postMessage与其他’*’作为起源.如果我在其中放置了一个URL,我会收到一个安全警告“安全错误http://xxx/处的内容可能无法从http://yyy/加载数据”,除非只在错误控制台(Ctrl Shift J)中,而不是在任何其他位置.我怀疑还有一些其他的东西需要设置在某个地方才能工作,但我还没弄清楚是什么.

Here’s a jsfiddle,稍加修改代码版本加载了我的域名文档,适用于Firefox和Chrome.

猜你在找的HTML5相关文章