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