en.javascript.info
en.javascript.info copied to clipboard
Incorrect information regarding access to the `document` of the `iframe`
Cross-window communication
Code:
<script>
iframe.onload = function() {
// we can get the reference to the inner window
let iframeWindow = iframe.contentWindow; // OK
try {
// ...but not to the document inside it
let doc = iframe.contentDocument; // ERROR // 🟢
} catch(e) {
alert(e); // Security Error (another origin)
}
// also we can't READ the URL of the page in iframe
try {
// Can't read URL from the Location object
let href = iframe.contentWindow.location.href; // ERROR
} catch(e) {
alert(e); // Security Error
}
// ...we can WRITE into location (and thus load something else into the iframe)!
iframe.contentWindow.location = '/'; // OK
iframe.onload = null; // clear the handler, not to run it after the location change
};
</script>
In the line labeled 🟢, we will not get any error when trying to access iframe.contentDocument.
MDN: HTMLIFrameElement: contentDocument property:
If the iframe and the iframe's parent document are Same Origin, returns a Document (that is, the active document in the inline frame's nested browsing context), $
\Huge\textcolor{red}{else}$ $\Huge\textcolor{red}{returns}$ $\Huge\textcolor{red}{null}$.