2016-07-06 63 views
0

我的要求,我需要得到iframe的內容,其中SRC低於其他域的是我的代碼PostMessage的閱讀iframe中的內容

<iframe id="receiver" src="http://demos.mattwest.io/post-message/receiver.html" width="500" height="200"> 
    <p>Your browser does not support iframes.</p> 
</iframe> 



<script> 
setTimeout(function(){ 
console.log($('#receiver').contents().find('body')); 
}, 2000); 

我得到了以下錯誤

jquery-2.2.4.js:3079 Uncaught SecurityError: Failed to read the 'contentDocument' property from 'HTMLIFrameElement': Blocked a frame with origin "null" from accessing a frame with origin "http://demos.mattwest.io". The frame requesting access has a protocol of "file", the frame being accessed has a protocol of "http". Protocols must match. 

我搜索了很多並發現關於PostMessage http://blog.teamtreehouse.com/cross-domain-messaging-with-postmessage

在這裏,他們正在發送消息,我的目標是獲取iframe內容我如何在我的場景中實現postMessage。

我不能能夠創造小提琴,它顯示出一些其他的問題https://jsfiddle.net/alokranjan39/re6aja0c/

如何解決這個請幫助!

回答

2

postMessage on iframe在本地不起作用。您需要在服務器上運行此代碼或以http而非file開頭的測試網站。內部.contents()

否則避免的jQuery,因爲它使用的postMessage()方法用的iframe通信。

純JavaScript方式:

使用.contentDocument

var iframer = document.getElementById('reciever'); 

var iframeBody = iframer.contentDocument.body; 

使用案例:

iframer.contentDocument.getElementById('someElementInIframe') 

等...

希望這有助於s

+0

仍然會出現同樣的錯誤我把代碼放在wamp www folder.if我要把我的代碼放在服務器中什麼是步驟來實現postmessage並得到相同的結果 – user3106347