gpt4 book ai didi

javascript - PostMessage 读取 Iframe 内容

转载 作者:行者123 更新时间:2023-12-02 14:26:05 25 4
gpt4 key购买 nike

我有一个要求,我需要获取 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。

我无法创建 fiddle ,它显示了一些其他问题 https://jsfiddle.net/alokranjan39/re6aja0c/

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

最佳答案

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

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

纯javascript方式:

使用.contentDocument

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

var iframeBody = iframer.contentDocument.body;

用例:

iframer.contentDocument.getElementById('someElementInIframe')

等等...

希望这有帮助

关于javascript - PostMessage 读取 Iframe 内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38228502/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com