2011-05-17 64 views
5

我使用JavaScript的几行创建IFRAME元素,然后我想发送一条消息,如:为什么html5 postMessage不适合我?

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:我试图在谷歌浏览器11和Firefox 4

预先感谢您。

回答

4

有两种可能出现的问题:

  1. 你调用callback之后的子帧加载 - 尝试在load事件或做一个setTimeout
  2. 我从来没有设法得到postMessage与任何其他'*'作为原点一起工作。如果我在那里放置一个URL,我会收到安全警告“安全错误:http://xxx/的内容不能从http://yyy/加载数据”,除非在错误控制台(Ctrl + Shift + J)中没有任何其他位置。我怀疑还有其他一些东西需要设置在某个地方才能工作,但我还没有弄清楚。

Here's a jsfiddle有一个稍微修改版本的代码,将文档加载到我的域中,适用于Firefox和Chrome。

+0

感谢robertc,它与setTimeout一起工作,我不必将'*'设置为原点(为了安全起见)。现在我想我会让iframe向父窗口发送消息,告诉它iframe已准备好,然后窗口会发送消息。你认为这是继续进行的正确方法吗? – 2011-05-17 14:54:46

+0

@JoãoPintoJerónimo听起来好像会起作用,它就像'iframe'的注册事件。 – robertc 2011-05-17 17:10:22

+0

它确实有效,我只是希望这是最好的解决方案。 – 2011-05-18 02:50:19