2011-05-17 81 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