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
预先感谢您。
感谢robertc,它与setTimeout一起工作,我不必将'*'设置为原点(为了安全起见)。现在我想我会让iframe向父窗口发送消息,告诉它iframe已准备好,然后窗口会发送消息。你认为这是继续进行的正确方法吗? – 2011-05-17 14:54:46
@JoãoPintoJerónimo听起来好像会起作用,它就像'iframe'的注册事件。 – robertc 2011-05-17 17:10:22
它确实有效,我只是希望这是最好的解决方案。 – 2011-05-18 02:50:19