Is there a way to get the title of a cross-origin sandboxed iframe's document?

28 Views Asked by At

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>

1

There are 1 best solutions below

0
David Bradshaw On

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.

top.postMessage(document.title, '*')

Then in the parent page you need to receive the message.

window.addEventListener("message", (event) => {
  alert(event.data)
}, false)