Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get DOM content of cross-domain iframe [duplicate]

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.

Thanks

like image 255
D-Nice Avatar asked May 29 '11 22:05

D-Nice


People also ask

How do I access cross-domain iframe?

To access cross-domain iframe, the best approach is to use Javascript's postMessage() method. This method provides a way to securely pass messages across domains.

How do I find if a click event on a cross-domain iframe?

You cannot detect click events in cross-domain iframe. However it's not reliable, loose focus does not mean a click, it could be user moving across the website using TAB .

What is #document in iframe?

Definition and Usage. The contentDocument property returns the Document object generated by a frame or iframe element. This property can be used in the host window to access the Document object that belongs to a frame or iframe element.

What is cross-domain iframes?

Learn about how cross-domain iframe can be used to safely circumvent browser restrictions on scripts that process code in a different domain. Applies to: Skype for Business 2015. Web applications that interact with UCWA 2.0 resources require a cross-domain iframe for all HTTP requests sent to UCWA 2.0.


2 Answers

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)

like image 140
Máthé Endre-Botond Avatar answered Sep 29 '22 21:09

Máthé Endre-Botond


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.

like image 32
Clément Gournay Avatar answered Sep 29 '22 19:09

Clément Gournay