我正在制作一个基本的网络浏览器,用 HTML 编写。我想访问文档的标题,以便您可以像普通浏览器中的选项卡一样查看它。通常,您可以使用
iframe.contentDocument.title
,但我的 iframe 是跨域和沙盒的,所以这似乎不起作用。有没有办法可以访问标题,或者这是不可能的?
这是一个例子:
const iframe = document.querySelector("iframe");
const span = document.querySelector("span");
document.querySelector("iframe").addEventListener("load", function() {
const title = iframe.contentDocument.title; // contentDocument is null
span.innerText = title;
});
body {
display: flex;
flex-direction: column;
margin: 0;
height: 100vh;
}
iframe {
flex-grow: 1;
}
<h1>Title: <span id="title"></span></h1>
<iframe src="https://www.bing.com" sandbox="allow-scripts"></iframe>
你不能直接访问它,但是,如果你可以在iFrame中的页面中添加JS,那么你可以在两个页面之间使用postMessage()。
iframe 中的每个页面都需要添加以下内容。
top.postMessage(document.title, '*')
然后在父页面你需要接收消息。
window.addEventListener("message", (event) => {
alert(event.data)
}, false)