【发布时间】:2010-12-06 22:45:29
【问题描述】:
如何获取 iframe src 页面标题,然后设置主页标题
【问题讨论】:
-
页面是否在同一个域中。如果不是,则意味着您尝试执行跨站点脚本。您仍然可以这样做,但您需要在 iframe 中打开的页面中设置域
标签: javascript jquery html iframe
如何获取 iframe src 页面标题,然后设置主页标题
【问题讨论】:
标签: javascript jquery html iframe
如果你想使用 jQuery:
var title = $("#frame_id").contents().find("title").html();
$(document).find("title").html(title);
只有页面在同一个域时才可以这样做,否则没用。
【讨论】:
授予 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>
【讨论】:
除非网页在 iframe 中与包含页面来自同一域,否则这是不可能的。
如果他们确实具有相同的域,请尝试以下操作:
document.title = document.getElementById("iframe").documentElement.title;
【讨论】:
contentDocument。除了在 IE6-7 中,您必须退回到非标准的contentWindow.document。 documentElement 是根 html 标记; title 属性位于 HTMLDocument 本身。
您可以共享标题和位置的一种方式:
document.write('<iframe src="http://www.yourwebsite.com/home.html?title='+document.title+'&url='+window.location+'" frameborder="0" scrolling="no"></iframe>');
然后就可以在home.html页面读取参数了。
【讨论】:
这可以使用页面上的事件侦听器来完成。它不是特别优雅,但我尝试过的浏览器都支持它(例如 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
【讨论】: