【问题标题】:Access to iframe content from another domain [duplicate]访问来自另一个域的 iframe 内容 [重复]
【发布时间】:2015-10-01 08:21:09
【问题描述】:

是否有任何可能的解决方法来获取包含来自另一个域的内容的 iframe 的 html,并根据它包含的内容使用 JS/jQuery 执行某些操作?由于相同的来源策略,AFAIK 浏览器隐藏了该内容,因此我不能直接访问它。

【问题讨论】:

  • 我不确定,但您可以尝试发送Access-Control-Allow-Origin 标头,将域列入白名单

标签: javascript jquery html iframe same-origin-policy


【解决方案1】:

如果您不想通过 iFrame 包含整个插件,该插件已经使用了很多脚本,并且该站点更像是一个包含本地体育俱乐部结果或其他“只读”信息的表格,您可以使用phpfile_get_contents()导入iframe。现在您可以对其内容进行样式化并通过 jQuery 定位它们。

例如,您有以下标记:

<html>
<!-- Some Head and Body parts, like navigation, sidebar, etc. -->
<div id="results">
<!-- Lots of results -->
</div>
</html>

您可以定位id="result 来识别要导入的部分的开头。

让我们定义你的目标:

$host = 'http://sportclub.de/results.html';

并导入他:

$filestring = file_get_contents($host);

由于您不想导入整个 url,您需要设置起点和终点。为了给你一个基本的想法,这是一个代码,它的工作方式类似于上面提到的概念:

<?php
$host = 'http://sportclub.de/results.html';
$filestring = file_get_contents($host);

$startpos = 0; //erstes Zeichen
while($pos = strpos($filestring, "<div id=\"results\"", $startpos))
{
    $string = substr($filestring, $pos, strpos($filestring, "</div>", $pos + 1) - $pos);
    echo $string."</div>";
    $startpos = $pos + 1;
}
$string = preg_replace("/(^¦\s)(http:\/\/)?(www\.)?[\.0-9a-zA-Z\-_~]+\.(com¦net¦org¦info¦name¦biz¦.+\.\w\w)((\/)?[0-9a-zA-Z\.\-_~#]+)?\b/ie","",$string);
?>

【讨论】:

  • 如果我无法访问后端,如果我只有“原样”的 iframe 内容并且需要确定它是否包含我正在寻找的内容,该怎么办?我所需要的只是对 iframe 的 DOM 的只读访问,以检查某些元素的 innerHTML
  • @yxfxmx 您的意思是您无法影响 iframe 嵌入网站的方式,您只能编辑 javascript 文件?或者您无法编辑 iframe 本身的内容(将通过 iframe 嵌入)?
猜你喜欢
  • 2012-10-31
  • 1970-01-01
  • 2019-08-23
  • 2014-08-02
  • 1970-01-01
  • 2015-07-31
  • 1970-01-01
  • 2011-12-09
  • 2012-09-04
相关资源
最近更新 更多