2016-07-06 122 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