我想从iframe网页中删除不必要的标头。其他SO页面上的解决方案似乎不起作用。一个例子:
<!DOCTYPE html>
<html>
<head>
<title>Modifying iFrame element</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.11.2.js"></script>
</head>
<body>
<p>Let's remove the header toolbar (class "header")</p>
<iframe id="wikipedia" src="https://en.m.wikipedia.org/wiki/Big_Ben" onload="removeHead()" style="width: 800; height: 500;"></iframe>
<script type="text/javascript">
function removeHead(){
$(function(){
var f=$('#wikipedia');
f.load(function(){
f.contents().find('.header').hide();
});
});
console.log("script complete");
};
</script>>
</body>
</html>
脚本运行但没有任何反应。我尝试过使用remove()而不是hide()和其他组合,没有运气。感谢您的帮助。
答案 0 :(得分:2)
由于浏览器的安全性,通常无法在iframe中使用或操作内容,除非它位于同一个域中。某些旧版浏览器可能不是这种情况,但现在肯定是。
这受Same-origin Policy规定。
另见本文:http://www.dyn-web.com/tutorials/iframes/refs/iframe.php
注意:只有文档具有相同的来源,才能进行这些跨文档交互。
可能的解决方案1
使用PHP Simple DOM Parser获取特定div元素或页面的某些部分:
include("./dom/simple_html_dom.php");
$html = file_get_html("https://en.m.wikipedia.org/wiki/Big_Ben");
$content = $html->find("#content", 0);
echo $content->innertext;
哪会产生这个:http://bibletools.info/script/wikipedia.php
可能的解决方案2
使用PHP Simple DOM Parser删除标题。如果您创建一个单独的PHP页面并将该php页面加载到iframe中,则不会有冲突的样式等。
include("./dom/simple_html_dom.php");
$html = file_get_html("https://en.m.wikipedia.org/wiki/Big_Ben");
$html->find('div.header', 0)->outertext = '';
$html->find('.top-bar', 0)->outertext = '';
echo $html;
哪会产生这个:http://bibletools.info/script/wikipedia1.php
注意:此解决方案可能稍慢,因为服务器必须首先加载页面,然后将其提供给用户。但实际上它非常有效。我一直使用这种方法取得了巨大的成功。