Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get IFrame's document, from JavaScript in main document

I have this HTML code:

<html>   <head>     <script type="text/javascript">       function GetDoc(x)       {         return x.document ||           x.contentDocument ||           x.contentWindow.document;       }        function DoStuff()       {         var fr = document.all["myframe"];         while(fr.ariaBusy) { }         var doc = GetDoc(fr);         if (doc == document)           alert("Bad");         else            alert("Good");       }     </script>   </head>   <body>     <iframe id="myframe" src="http://example.com" width="100%" height="100%" onload="DoStuff()"></iframe>   </body> </html> 

The problem is that I get message "Bad". That mean that the document of iframe is not got correctly, and what is actualy returned by GetDoc function is the parent document.

I would be thankful, if you told where I do my mistake. (I want to get document hosted in IFrame.)

Thank you.

like image 960
ernestasju Avatar asked Oct 22 '10 16:10

ernestasju


People also ask

How do I get an iframe document?

getIframeContent(frameId): It is used to get the object reference of an iframe. contentWindow: It is a property which returns the window object of the iframe. contentWindow. document: It returns the document object of iframe window.

Can JavaScript access iframe content?

You could use . contents() method of jQuery. The . contents() method can also be used to get the content document of an iframe, if the iframe is on the same domain as the main page.

How do I get iframe from parent file?

To access elements of parent window from iframe with JavaScript, we can use the window. parent. document property to get the parent window's document.


2 Answers

You should be able to access the document in the IFRAME using the following code:

document.getElementById('myframe').contentWindow.document 

However, you will not be able to do this if the page in the frame is loaded from a different domain (such as google.com). THis is because of the browser's Same Origin Policy.

like image 94
pkaeding Avatar answered Oct 15 '22 20:10

pkaeding


The problem is that in IE (which is what I presume you're testing in), the <iframe> element has a document property that refers to the document containing the iframe, and this is getting used before the contentDocument or contentWindow.document properties. What you need is:

function GetDoc(x) {     return x.contentDocument || x.contentWindow.document; } 

Also, document.all is not available in all browsers and is non-standard. Use document.getElementById() instead.

like image 35
Tim Down Avatar answered Oct 15 '22 22:10

Tim Down