获取跨域 iframe 的 DOM 内容

我有一个跨域网站的 iframe。我想阅读 iframe 的 DOM,我认为这是可能的,因为使用检查器,我甚至可以修改 iframe 的 DOM。不管我怎么解读它,我都会遇到同样的原始策略。我所需要的,是从 iframe 加载到本地 DOM 中的内容。我原以为它会像 $(document.body).find('iframe').html()一样简单,但是返回的是空字符串。

我真的希望有一种方法可以做到这一点,因为我在过去几天里所做的工作都是建立在这是可行的基础上的。

谢谢

215856 次浏览

If you have access to the iframed page you could use something like easyXDM to make function calls in the iframe and return the data.

If you don't have access to the iframed page you will have to use a server side solution. With PHP you could do something quick and dirty like:

    <?php echo file_get_contents('http://url_of_the_iframe/content.php'); ?>

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.

EDIT

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

There's a workaround to achieve it.

  1. First, bind your iframe to a target page with relative url. The browsers will treat the site in iframe the same domain with your website.

  2. In your web server, using a rewrite module to redirect request from the relative url to absolute url. If you use IIS, I recommend you check on IIRF module.

If you have an access to that domain/iframe that is loaded, then you can use window.postMessage to communicate between iframe and the main window.

Read the DOM with JavaScript in iframe and send it via postMessage to the top window.

More info here: https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage

There is a simple way.

  1. You create an iframe which has for source something like "http://your-domain.com/index.php?url=http://the-site-you-want-to-get.com/unicorn

  2. Then, you just get this url with $_GET and display the contents with file_get_contents($_GET['url']);

You will obtain an iframe which has a domain same than yours, then you will be able to use the $("iframe").contents().find("body") to manipulate the content.