Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the element inside an iframe element in Javascript?

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>
like image 454
Thomson Avatar asked Oct 20 '11 13:10

Thomson


1 Answers

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/>
like image 178
mplungjan Avatar answered Oct 06 '22 05:10

mplungjan