I am making a basic web browser, written in HTML. I'd like to access the title of the document, so that you can see it like a tab in a normal browser. Usually, you can use iframe.contentDocument.title, but my iframe is cross-origin and sandboxed so this doesn't seem to work. Is there a way that you can access the title anyway, or is this impossible?
Here's an example:
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>
You cannot access it directly, however, if you can add JS to the page in the iFrame, then you can use postMessage() between the two pages.
Every page in your iframe would need to add the following.
Then in the parent page you need to receive the message.