Monday, June 3, 2024
119
rated 0 times [  124] [ 5]  / answers: 1 / hits: 17702  / 13 Years ago, thu, october 20, 2011, 12:00:00

I have a element as below inside the document, I could get the iframe element by document.getElementById('iframe_id'), but how to get the element inside this iframe? I tried iframeElement.contentWindow, and the returned DOMWindow has no properties. Also tried iframeElement.docuemnt and iframeElement.contentDocument, both of them are undefined. How can I get it? I am using the latest Chrome in my experiment.



Here is the iframe element



<iframe id='iframe_id'>
<html>
<body>many content here</body>
</html>
</iframe>

More From » google-chrome

 Answers
17

You can ONLY interrogate content in an iframe if the content has the same protocol, domain and port number as the script that interrogates it. It is called SAME ORIGIN



If that is the case, then this code will show the content. If not - you cannot access the iframe from a normal script in a normal html page



Demo - tested in IE8, Chrome 13 and Fx6



function showIframeContent(id) {
var iframe = document.getElementById(id);
try {
var doc = (iframe.contentDocument)? iframe.contentDocument: iframe.contentWindow.document;
alert(doc.body.innerHTML);
}
catch(e) {
alert(e.message);
}
return false;
}


<iframe id='iframe_id1' src=javascript:parent.somehtml()> </iframe>
<br/>
<a href=# onclick=return showIframeContent('iframe_id1')>Show</a>
<hr/>

<iframe id='iframe_id2' src=http://plungjan.name/> </iframe>
<br/>
<a href=# onclick=return showIframeContent('iframe_id2')>Show</a>
<hr/>

[#89514] Wednesday, October 19, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
mahogany

Total Points: 645
Total Questions: 107
Total Answers: 98

Location: Israel
Member since Wed, Apr 14, 2021
3 Years ago
mahogany questions
;