【问题标题】:How to get the html title from the page that loads in the iframe?如何从 iframe 中加载的页面获取 html 标题?
【发布时间】:2015-05-03 04:48:46
【问题描述】:

这肯定是一个受欢迎的问题.. 但是我没有阅读这些内容就没有发布它.. 80% 的人没有有效的答案.. 只是谈论同源政策.. 我的 php 页面 r都在同一个域中..

所以这就是我在大多数有逻辑答案的地方得到的结果..

    $(document).ready(function() {
       document.title=$("#mainFrame").contents().find("head").find('title').html();
    });

我的 iframe 的 id 是“mainFrame”。我想获取在 iframe 中加载的页面的标题,并每次都将该标题设置为父级的标题。

那么有什么有效的方法可以做到这一点吗?这个 sn-p 不起作用..我试过..它返回 undefined!

【问题讨论】:

  • 你贴的代码 sn-p 是在主页还是在 iframe 中?另外,您是否尝试过在该行设置断点以检查它何时运行?也许它会在加载 iframe 之前运行,这将是一个非常可能的选择。
  • 这是在包含 iframe 的父页面上! -_-
  • 在页面开始和结束时都尝试了 sn-p .. 不工作!
  • 为什么这个问题被否决了?! -_- 是的,这很明显.. 仍然没有可行的解决方案.. 我能做些什么!

标签: javascript php jquery html iframe


【解决方案1】:
var title = $( "#frame_id").contents( ).find( "title").html( );
$( document).find( "title").html( title);

【讨论】:

  • 老兄,我在这个之前尝试过.. 不工作.. 至少在 firefox 37 上没有
  • 平面旧javascript方式:document.title = document.getElementById("main-content-iframe").contentDocument.title;
  • 要清楚它总是返回项目的根路径..而不是页面 iframe 加载的路径
【解决方案2】:

你不需要 jQuery。在你的父母中做:

var iFrame = document.getElementById('mainFrame'), // Or $('#mainFrame')[0],
    iFrameDoc = iFrame.contentWindow.document || iFrame.contentDocument;

document.title = iFrameDoc.title;

contentDocument 是 iframe 的文档。

【讨论】:

  • 当我使用这个时..返回绝对路径..这是“localhost/projectName
  • 要清楚它总是返回项目的根路径..而不是页面 iframe 加载的路径
  • 您确定您的文档有标题吗?或者标题不是根路径?尝试更新这篇文章。
  • 添加到这一点 - 当父子节点的来源/域不同时,浏览器会阻止这种对“contentWindow”或“contentDocument”的访问
猜你喜欢
  • 2011-08-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-04-09
  • 2017-07-14
  • 2014-11-21
  • 2010-12-06
  • 1970-01-01
相关资源
最近更新 更多