Javascript iframe innerHTML
时间:2020-03-06 14:46:50 来源:igfitidea点击:
有谁知道如何从IFRAME中获取HTML,我尝试了几种不同的方法:
document.getElementById('iframe01').contentDocument.body.innerHTML
document.frames['iframe01'].document.body.innerHTML
document.getElementById('iframe01').contentWindow.document.body.innerHTML
等等
解决方案
如果我们查看JQuery,则可以执行以下操作:
<iframe id="my_iframe" ...></iframe>
$('#my_iframe').contents().find('html').html();
假设iframe父级和子级都位于同一服务器上,这归因于Java中的"相同来源策略"。
我认为这是我们想要的:
window.frames['iframe01'].document.body.innerHTML
编辑:
我有很好的权限,尽管它在IE(我测试过的地方)中能完美运行,但它不能在Chrome和Firefox中使用。回想起来,那是一个大错误
这将起作用:
window.frames[0].document.body.innerHTML
我了解这并不是所要的,但我不想删除答案,因为我认为它有位置。
我喜欢下面的@ravz的jquery答案。
不要忘记,由于安全原因,我们不能跨域。
因此,如果是这种情况,则应使用JSON。
拥有类似以下内容的方法将起作用。
<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;
}

