Reputation: 43
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.
Upvotes: 3
Views: 2863
Reputation: 6013
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"></script>
<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.
Upvotes: 2
Reputation: 8781
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
Upvotes: 0