Javascript Iframe innerHTML

2019-01-05 05:10发布

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

9条回答
Deceive 欺骗
2楼-- · 2019-01-05 05:30
document.getElementById('iframe01').outerHTML
查看更多
做自己的国王
3楼-- · 2019-01-05 05:31

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 = document.getElementById(id); 

var doc; 

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

doc.body.innerHTML = text; 

  }
查看更多
Animai°情兽
4楼-- · 2019-01-05 05:34

You can use the contentDocument or contentWindow property for that purpose. Here is the sample code.

function gethtml()
{
var x=document.getElementById("myframe");
var y=(x.contentWindow || x.contentDocument);
if (y.document)y=y.document;
alert(y.body.innerHTML);
}

here, my frame is the id of your iframe. Note: You can't extract the content out of an iframe from a src outside you domain.

查看更多
看我几分像从前
5楼-- · 2019-01-05 05:40

Conroy's answer was right. In the case you need only stuff from body tag, just use:

$('#my_iframe').contents().find('body').html();
查看更多
Anthone
6楼-- · 2019-01-05 05:42

You can get html out of an iframe using this code iframe = document.getElementById('frame'); innerHtml = iframe.contentDocument.documentElement.innerHTML

查看更多
Viruses.
7楼-- · 2019-01-05 05:43

I think this is what you want:

window.frames['iframe01'].document.body.innerHTML 

EDIT:

I have it on good authority that this won't work in Chrome and Firefox although it works perfectly in IE, which is where I tested it. In retrospect, that was a big mistake

This will work:

window.frames[0].document.body.innerHTML 

I understand that this isn't exactly what was asked but don't want to delete the answer because I think it has a place.

I like @ravz's jquery answer below.

查看更多
登录 后发表回答