【问题标题】:Insert HTML <base> into iframe将 HTML <base> 插入 iframe
【发布时间】:2017-11-11 10:15:38
【问题描述】:

我正在尝试将base HTML 标记插入加载远程 URL 的 iframe。

<iframe name="frame" id="frame" src="proxy.php" width="550" height="150"></iframe>

Proxy.php的内容如下

$url = 'https://theurl.com/buyflow/buyflow-localization.html'; 
$probe = file_get_contents($url);
echo $probe;

框架正确加载所有绝对链接,但在尝试加载相对链接时,它指的是我的 localhost(本地 Web 服务器)@ 127.0.0.1

【问题讨论】:

  • 您能否说明插入base 标签的方式和位置?目前尚不清楚您是使用脚本执行此操作还是将其写入文件。也不清楚这些文件的位置以及您期望的结果。
  • @YakovL 我希望 theurl.com"> 嵌套在 标记中。我需要通过 proxy.php 完成此操作,以便 iframe 在远程服务器上查找资源(图像、脚本等)(希望这是有道理的)(不幸的是,由于 CORS,我无法编辑远程 URL 源。
  • 好的,现在我明白了您要实现的目标和原因。你说你试图插入base 标签,你能说明你是如何尝试的吗?
  • theurl.com">'; $url = 'theurl.com/buyflow/buyflow-localization.html'; $probe = file_get_contents($url);回声$探针; ?> 这段代码可以加载所有内容,因此任务完成。但是,如何在 iframe DOM 中实际插入代码?

标签: php javascript-objects


【解决方案1】:

您的base 应该在head 元素内。一个可能的解决方案是使用DOMDocument 类来操作文档。像这样的:

$dirUrl = 'https://theurl.com/buyflow/';
$url = $dirUrl . 'buyflow-localization.html';
$probe = file_get_contents($url);

$doc = new DOMDocument();
$doc->loadHTML($probe);

$head = $doc->getElementsByTagName('head')[0]; // try also ->item(0) instead of [0]
$bases = $head->getElementsByTagName('base');
if(count($bases) == 0) {
    $base = $doc->createElement('base');
    $head->appendChild($base);
} else
    $base = $bases[0]; // same here
$base->setAttribute('href', $dirUrl);

echo $doc->saveHTML();

【讨论】:

  • 哇,这正是我想要做的!非常感谢!
  • @Rain 顺便说一句,这对你有用吗?看起来 [0] 实际上应该是 -&gt;item(0)
  • 不,它不能完美地工作,但它确实帮助我确定 标记已经存在。现在我只需要弄清楚如何替换它:)
  • 在将 [0] 替换为 ->item(0) 之前和之后,我得到以下信息:致命错误:未捕获的 TypeError:传递给 DOMNode::appendChild() 的参数 1 必须是 DOMNode 的实例, null 在 C:\xampp\htdocs\mo\proxy.php:14 中给出
  • @Rain 出现错误,尝试用$doc-&gt;createElement('base'); 替换DOMDocument::createElement('base');。至于您的情况,您设置了 else 操作。我会修改代码,但请记住,我还没有测试过。
猜你喜欢
  • 1970-01-01
  • 2016-10-30
  • 2016-10-02
  • 1970-01-01
  • 1970-01-01
  • 2011-02-16
  • 1970-01-01
  • 2013-05-19
  • 2016-01-20
相关资源
最近更新 更多