2015-01-16 26 views
0

所以我一直在關注使用window.postMessage()在容器window和它的iframe內容window之間進行通信的很多教程。JS:無法讓window.parent使用postMessage

但是,我遇到了無法將收件人的window作爲目標的問題,我可以將其稱爲postMessage(),或者我獲得的對象是空的。以下是一些解釋,您可以通過查看Github repo中的代碼來關注我。

我有兩個項目,iframe-contentiframe-container,完全符合你的期望。這些項目中的每一個都需要定位window對象才能夠調用window.postMessage()

在容器的情況下,運行此代碼

var childWindow = document.getElementById('iframeContent').contentWindow 
console.log('childWindow: ', childWindow); 

不會導致錯誤,但返回的window對象沒有任何財產。 See the code

同樣,在內容

var parentWindow = $window.parent; 
console.log('parentWindow: ', parentWindow); 

這樣做同樣的作爲與容器解釋。 See the code

看空window對象我的意思是截圖:

enter image description here

在這兩種情況下,調用postMessage()函數返回沒有錯誤,但實際上失敗。

我可能忽略了什麼?我應該看什麼?任何指導表示讚賞,謝謝。

+0

什麼'的document.getElementById( 'iframeContent')。contentWindow.postMessage'收益(而不必調用括號!)? 在Chrome中,窗口對象似乎總是空的,同時在Firefox中顯示一些屬性。 –

+0

@RainerRillke:我依靠你的評論和FF和Safari的檢查,我忘記了。 FF就像你說的那樣好,Saf正在抱怨安全。也許提供關於其他窗口的信息是不安全的事情,所以Chrome顯示沒有錯誤,但沒有內容?我在沒有paren的情況下檢查了'postMessage',它顯示'function(){[native code]}'。我添加了一些日誌記錄,現在它工作正常。我一定誤解了我的調試。謝謝! – jansensan

+0

隨時回答你自己的問題 –

回答

-1

聽起來可能像你試圖訪問跨域iframe。確保你設置了正確的來源和事件監聽器的API。

https://developer.mozilla.org/en-US/docs/Web/API/Window.postMessage

記住的iframe需要監聽的消息

window.addEventListener("message", receiveMessage, false); 

function receiveMessage(event) 
{ 
    if (event.origin !== "http://example.org:8080") 
    return; 

    // ... 
} 
+0

我已經在當前窗口中有偵聽器https://github.com/jansensan/test-iframe-comm-with-post/blob/master/post-office/src/post-office .js#L84我會在原始文章中添加一張圖片,以顯示我的意思是空的收件人窗口。 – jansensan