Get DOM content of cross-domain iframe

I have an iframe for a cross-domain site. I want to read the iframe DOM, which I thought was possible because, using the inspector, I can even change the iframe's DOM. However, whenever I try to read it, I come across the same origin policy. All I want is the content loaded into my local DOM from the iframe. I thought it would be as simple as $(document.body).find('iframe').html() , but it returns an empty string.

I really hope that there is a way to do this, since the work that I have done over the past few days has been based on the fact that this is possible.

thank

+47
javascript jquery html html5 iframe
May 29 '11 at 22:47
source share
5 answers

You can not. XSS protection . Cross site content cannot be read by javascript. No main browser will allow you to do this. Sorry, but this is a design flaw, you should give up this idea.

EDIT

Please note that if you are editing access to a website loaded in an iframe, you have two options:

Access-Control-Allow-Origin: http://foo.example

where http://foo.example is the domain that hosts the page with the iframe in it

+52
May 29 '11 at 22:58
source share

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

If you do not have access to the iframed page, you will have to use a server-side solution. With PHP you can do something quick and dirty, like:

  <?php echo file_get_contents('http://url_of_the_iframe/content.php'); ?> 
+6
May 29 '11 at 22:52
source share

There is an easy way.

You will get an iframe that has a domain other than yours, then you can use $ ("iframe"). contents (). find ("body") for content management.

+6
Jan 28 '16 at 5:48
source share

If you have access to this bootable domain / iframe, you can use window.postMessage to communicate between the iframe and the main window.

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

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

+4
Aug 28 '15 at 7:25
source share

There is a workaround to achieve this.

  • First, bind your iframe to a landing page with a relative url. Browsers will process the site in an iframe in the same domain from your site.

  • On your web server, using a rewrite module to redirect the request from a relative URL to an absolute URL. If you are using IIS, I recommend that you check the IIRF module .

-3
May 30 '11 at 4:58 a.m.
source share



All Articles