Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get element from within an iFrame

How do you get a <div> from within an <iframe>?

like image 603
joepour Avatar asked Jul 06 '09 18:07

joepour


People also ask

Can I get element inside iframe?

contents() can get both text nodes and HTML elements. That's why one can get document contents of an iframe by using it. Note that the iframe and page have to be on the same domain.

How do you know if an element is inside an iframe?

In short, to check if a page is in an iframe, you need to compare the object's location with the window object's parent location. If they are equal, then the page is not in an iframe; otherwise, a page is in an iframe.

How do I access iframe?

To get the element in an iframe, first we need access the <iframe> element inside the JavaScript using the document. getElementById() method by passing iframe id as an argument. const iframe = document.

What is #document inside iframe?

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.


2 Answers

var iframe = document.getElementById('iframeId'); var innerDoc = (iframe.contentDocument) ? iframe.contentDocument : iframe.contentWindow.document; 

You could more simply write:

var iframe = document.getElementById('iframeId'); var innerDoc = iframe.contentDocument || iframe.contentWindow.document; 

and the first valid inner doc will be returned.

Once you get the inner doc, you can just access its internals the same way as you would access any element on your current page. (innerDoc.getElementById...etc.)

IMPORTANT: Make sure that the iframe is on the same domain, otherwise you can't get access to its internals. That would be cross-site scripting.

like image 104
geowa4 Avatar answered Oct 14 '22 22:10

geowa4


Do not forget to access iframe after it is loaded. Old but reliable way without jQuery:

<iframe src="samedomain.com/page.htm" id="iframe" onload="access()"></iframe>  <script> function access() {    var iframe = document.getElementById("iframe");    var innerDoc = iframe.contentDocument || iframe.contentWindow.document;    console.log(innerDoc.body); } </script> 
like image 32
lukyer Avatar answered Oct 14 '22 22:10

lukyer