如何获取iframe src页面标题并设置主页面标题
如果你想使用jQuery来完成:
var title = $("#frame_id").contents().find("title").html();
$(document).find("title").html(title);
只有当页面在同一域名下时才能使用,否则它是无用的。
除非iframe中的网页与包含页面来自同一域,否则无法实现。
如果它们具有相同的域名,则尝试以下操作:
document.title = document.getElementById("iframe").documentElement.title;
contentDocument
。在IE6-7中,您必须退回到非标准的contentWindow.document
。 documentElement
是根HTML标记;title
属性位于HTMLDocument本身上。 - bobince假设 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>
可以使用页面上的事件监听器来实现。虽然不是特别优雅,但我尝试过的浏览器都支持它(包括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);
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页面上读取参数。