繁体   English   中英

使用jquery从javascript获取iframe页面标题

[英]get iframe page title from javascript using jquery

如何获取 iframe src 页面标题,然后设置主页标题

如果你想使用 jQuery 做到这一点:

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

只有当页面在同一个域上时才能这样做,否则它没有用。

授予 iframes 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>

除非网页在 iframe 中与包含页面来自同一个域,否则这是不可能的。

如果它们确实具有相同的域,请尝试以下操作:

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

这可以使用页面上的事件侦听器来完成。 它不是特别优雅,但我尝试过的浏览器都支持它(比如 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

您可以共享标题和位置的一种方式:

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM