views:

387

answers:

2

Does anyone know how to get the HTML out of an IFRAME? I have tried several different ways:

document.getElementById('iframe01').contentDocument.body.innerHTML, document.frames['iframe01'].document.body.innerHTML, document.getElementById('iframe01').contentWindow.document.body.innerHTML, etc

but none of them worked.

I believe the reason they're not working is that the content of my iframe doesn't have a body tag (I'm loading XML). Any other way to get all the contents of the iframe? I am open to jQuery too.

This:

document.getElementById('iframe01').contentWindow.document.body.innerHTML

works fine in the IE, but this:

document.getElementById('iframe01').contentDocument.body.innerHTML

does not work for FF.

A: 

I had a similar issue a while ago. Try using:

document.frames["iframe0"].contentWindow.document.body.innerHTML

That should work for both IE and FF

Yo Momma
it works if only i have body tag within the iframe. but in mycase the body tag is not there because i am opening an xml with xsl in the iframe. it shows no body tag it shows one <result> tag which also i cant access
Arjun Singh
+2  A: 

Since you tagged this jQuery, I assume you'd appreciate an answer in jQuery to get past the cross-browser issues.

$("#iframe01").contents()

will get you into the jQuery object for the contents of the iframe. You can work from there. Security issues may prevent you from getting the actual HTML content (you'll get an error like "permission denied to get property htmldocument").

Full sample code:

<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"&gt;&lt;/script&gt;
<script>
$(function() {
    $("#clickme").click(function() {
      alert($("#iframe01").contents().find("body").html());
      return false;
    });     
});
</script>
</head>
<body>
  <p id="hello">Hello World, there's an iframe below this. <a href="#" id="clickme">Click me!</a></p>
  <iframe id="iframe01" src="iframe_content.html"></iframe>
</body>
</html>

Note that you will have to load the iframe from the same domain and be sure the iframe has loaded before doing anything.

dyve
iframe_content.html contains your example <result> <h1>Title</h1><div>Rest content</div> <div>Another Content</div> </result>
dyve