【问题标题】:PostMessage Read Iframe contentPostMessage 读取 iframe 内容
【发布时间】:2016-11-08 18:29:28
【问题描述】:

我有一个要求,我需要获取 iframe 的内容,其中 src 属于另一个域,下面是我的代码

<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/

如何解决这个问题请帮忙!!!

【问题讨论】:

    标签: javascript jquery iframe cross-domain


    【解决方案1】:
    iframe 上的

    postMessage 将无法在本地工作。您需要在服务器上运行此代码或以 http 而不是 file 开头的测试网站。

    否则避免使用 jQuery,因为它使用 .contents() 内部的 postMessage() 方法与 iframe 进行通信。

    纯javascript方式:

    使用.contentDocument

    var iframer = document.getElementById('reciever');
    
    var iframeBody = iframer.contentDocument.body;
    

    用例:

    iframer.contentDocument.getElementById('someElementInIframe')
    

    等等……

    希望对你有帮助

    【讨论】:

    • 仍然出现同样的错误,我将代码放在 wamp www 文件夹中。如果我要将代码放在服务器中,实现 postmessage 并接收相同结果的步骤是什么
    猜你喜欢
    • 1970-01-01
    • 2011-10-10
    • 2012-08-20
    • 1970-01-01
    • 1970-01-01
    • 2013-02-26
    • 1970-01-01
    • 2017-03-02
    相关资源
    最近更新 更多