views:

13430

answers:

5

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

+1  A: 

If you take a look at JQuery, you can do something like:

<iframe id="my_iframe" ...></iframe>

$('#my_iframe').contents().find('html').html();

This is assuming that your iframe parent and child reside on the same server, due to the Same Origin Policy in Javascript.

ConroyP
You are grabbing the innerHTML of the html element and not the body, and this is a pretty backwards method to do it. When there are native DOM properties for retrieving what you want (e.g. .body) you should avoid the overhead of a find call.
Prestaul
+2  A: 

I think this is what you want:

window.frames['iframe01'].document.body.innerHTML
wcm
And if you want to be more unambiguous you could say: window.frames['iframe01'].document.body.innerHTML
Prestaul
I agree. Thanks
wcm
+1  A: 

Don't forget that you can not cross domains because of security.

So if this is the case, you should use JSON.

Biri
A: 

i find it handy to open the iframe in it's own window, and just view the innerHTML as normal (ie, propreties and copy the address. firefox, right click 'This Frame, Open Frame in New window')

cheeves
+1  A: 

Having something like the following would work.

<iframe id = "testframe" onload = populateIframe(this.id);></iframe>

// The following function should be inside a script tag

function populateIframe(id) { 

    var text = "This is a Test"
var iframe = getObj(id); 

var doc; 

if(iframe.contentDocument) { 
    doc = iframe.contentDocument; 
} else {
    doc = iframe.contentWindow.document; 
}

doc.body.innerHTML = text; 

  }
cypher