使用jQuery从JavaScript获取iframe页面标题

7
如何获取iframe src页面标题并设置主页面标题

1
页面是否在同一域中。如果不是,那就意味着你试图进行跨站脚本攻击。你仍然可以这样做,但需要在你打开的iframe页面中设置域名。 - Emrah GOZCU
5个回答

8

如果你想使用jQuery来完成:

var title = $("#frame_id").contents().find("title").html();
$(document).find("title").html(title);

只有当页面在同一域名下时才能使用,否则它是无用的。


3

除非iframe中的网页与包含页面来自同一域,否则无法实现。

如果它们具有相同的域名,则尝试以下操作:

document.title = document.getElementById("iframe").documentElement.title;

1
contentDocument。在IE6-7中,您必须退回到非标准的contentWindow.documentdocumentElement是根HTML标记;title属性位于HTMLDocument本身上。 - bobince

3

假设 iframe 的 src 和父文档的 src 是同一个域名:

父文档:

<html>
<head><title>Parent</title>
<body>
   <iframe id="f" src="someurl.html"></iframe>
   <script>
       //if the parent should set the title, here it is
       document.title = document.getElementById('f').contentWindow.document.title;
   </script>
</body>
</html>

someurl.html:

<html>
<head><title>Child</title>
<body>
  <script>
       //if the child wants to set the parent title, here it is
       parent.document.title = document.title;
       //or top.document.title = document.title;

  </script>
</body> 
</html>

2
在Chrome中,iframe.contentWindow.document返回null。 - msbg

1

可以使用页面上的事件监听器来实现。虽然不是特别优雅,但我尝试过的浏览器都支持它(包括IE9+、Firefox和Chrome)。

在您的主站点页面中添加以下JavaScript代码:

function setPageTitle(event) {
    var newPageTitle = event.data
    // your code for setting the page title and anything else you're doing
}
addEventListener('message', setPageTitle, false);

在 iFrame 中,您需要添加以下脚本:
var targetOrigin = "http://your.domain.com"; // needed to let the browser think the message came from your actual domain
parent.postMessage("New page title", targetOrigin); // this will trigger the message listener in the parent window

为了获得更多的浏览器支持,请使用以下代码:if (window.addEventListener) { window.addEventListener("message", listener); } else { // IE8 window.attachEvent("onmessage", listener); } - German Khokhlov

1

你可以分享标题和位置的一种方法是:

document.write('<iframe src="http://www.yourwebsite.com/home.html?title='+document.title+'&url='+window.location+'" frameborder="0" scrolling="no"></iframe>');

然后你可以在home.html页面上读取参数。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接