有谁知道如何从 IFRAME 中获取 HTML 我尝试了几种不同的方法:
document.getElementById('iframe01').contentDocument.body.innerHTML
document.frames['iframe01'].document.body.innerHTML
document.getElementById('iframe01').contentWindow.document.body.innerHTML
等
我认为这就是你想要的:
window.frames['iframe01'].document.body.innerHTML
编辑:
我有很好的权威,这在Chrome和Firefox中不起作用,尽管它在IE中运行良好,这是我测试它的地方。 回想起来,这是一个很大的错误
。这将起作用:
window.frames[0].document.body.innerHTML
我知道这不是完全被问到的,但不想删除答案,因为我认为它有一席之地。
我喜欢下面@ravz的jquery答案。
拥有类似以下内容的内容将起作用。
<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;
}
如果你看看JQuery,你可以做一些事情:
<iframe id="my_iframe" ...></iframe>
$('#my_iframe').contents().find('html').html();
这是假设您的 iframe 父级和子级驻留在同一台服务器上,这是由于 Javascript 中的同源策略。
康罗伊的回答是对的。如果您只需要正文标签中的内容,只需使用:
$('#my_iframe').contents().find('body').html();
可以使用 contentDocument 或 contentWindow 属性来实现此目的。下面是示例代码。
function gethtml() {
const x = document.getElementById("myframe")
const y = x.contentWindow || x.contentDocument
const z = y.document ? y.document : y
alert(z.body.innerHTML)
}
在这里,myframe
是iframe的ID。注意:您无法从网域外的 src 中提取 iframe 中的内容。
不要忘记,由于安全性的原因,您不能跨域。
因此,如果是这种情况,则应使用 JSON。
此解决方案的工作方式与 iFrame 相同。我创建了一个PHP脚本,可以从其他网站获取所有内容,最重要的是您可以轻松地将自定义jQuery应用于该外部内容。请参考以下脚本,该脚本可以从其他网站获取所有内容,然后您也可以应用cusom jQuery/JS。此内容可以在任何地方、任何元素或任何页面内使用。
<div id='myframe'>
<?php
/*
Use below function to display final HTML inside this div
*/
//Display Frame
echo displayFrame();
?>
</div>
<?php
/*
Function to display frame from another domain
*/
function displayFrame()
{
$webUrl = 'http://[external-web-domain.com]/';
//Get HTML from the URL
$content = file_get_contents($webUrl);
//Add custom JS to returned HTML content
$customJS = "
<script>
/* Here I am writing a sample jQuery to hide the navigation menu
You can write your own jQuery for this content
*/
//Hide Navigation bar
jQuery(".navbar").hide();
</script>";
//Append Custom JS with HTML
$html = $content . $customJS;
//Return customized HTML
return $html;
}
document.getElementById('iframe01').outerHTML
如果你在 Firefox 上安装了 ForceCORS 过滤器,你可以从另一个域获取源代码。当您打开此过滤器时,它将绕过浏览器中的安全功能,即使您尝试阅读其他网页,您的脚本也会起作用。例如,您可以在 iframe 中打开 FoxNews.com,然后读取其源代码。现代 Web brwosers 默认拒绝此功能的原因是,如果另一个域包含一段 JavaScript,并且您正在阅读该内容并将其显示在您的页面上,则可能包含恶意代码并构成安全威胁。因此,每当您在页面上显示来自另一个域的数据时,您都必须提防这种真正的威胁,并在显示文本之前实现一种方法来过滤掉文本中的所有JavaScript代码。请记住,当一段假定的原始文本包含一些包含在脚本标签中的代码时,当您在页面上显示它时,它们不会显示,但它们会运行!所以,意识到这是一个威胁。
http://www-jo.se/f.pfleger/forcecors
此代码从 iframe 中获取 htmliframe = document.getElementById('frame');innerHtml = iframe.contentDocument.documentElement.innerHTML