获取跨域 iframe 的 DOM 内容

2022-01-30 00:00:00 iframe jquery javascript html

我有一个跨域网站的 iframe.我想读取 iframe 的 DOM,我认为这是可能的,因为使用检查器,我什至可以修改 iframe 的 DOM.然而,我尝试阅读它的每一种方式,都会遇到相同的来源政策.我想要的只是从 iframe 加载到本地 DOM 中的内容.我认为它会像 $(document.body).find('iframe').html() 一样简单,但它返回的是空字符串.

I have an iframe for a cross-domain site. I want to read the DOM of the iframe, which I believed was possible because using the inspector, I can even modify the DOM of an iframe. Every way I attempt to read it, however, I run into the same origin policy. All I want, is the content loaded in my local DOM, from the iframe. I thought it would be as simple as $(document.body).find('iframe').html(), but that's returning the empty string.

我真的希望有一种方法可以做到这一点,因为我过去几天所做的工作都是基于这个可行的.

I really hope there's a way to do this since the work I've been doing for the last several days has been predicated on this being do-able.

谢谢

推荐答案

你不能.XSS 保护.javascript 无法读取跨站点内容.没有主流浏览器会允许你这样做.对不起,这是一个设计缺陷,你应该放弃这个想法.

You can't. XSS protection. Cross site contents can not be read by javascript. No major browser will allow you that. I'm sorry, but this is a design flaw, you should drop the idea.

编辑

请注意,如果您对加载到 iframe 中的网站具有编辑权限,则可以使用 postMessage(另请参阅浏览器兼容性)

Note that if you have editing access to the website loaded into the iframe, you can use postMessage (also see the browser compatibility)

相关文章