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>
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/>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With