Skip to content

How to get iframe's document

https://javascript.info/cross-window-communication#iframe-wrong-document-pitfall

The contentDocument accessed immediately is not the same as the contentDocument accessed after the iframe is loaded.

js
<iframe src="/" id="iframe"></iframe>

<script>
  let oldDoc = iframe.contentDocument;
  iframe.onload = function() {
    let newDoc = iframe.contentDocument;
    // the loaded document is not the same as initial!
    alert(oldDoc == newDoc); // false
  };
</script>

So, we can to access the correct contentDocument after the iframe is loaded.

But it is too late, if we need to access the correct contentDocument as soon as possible. We can use setInterval to check the contentDocument is loaded.

js
<iframe src="/" id="iframe"></iframe>

<script>
  let oldDoc = iframe.contentDocument;

  // every 100 ms check if the document is the new one
  let timer = setInterval(() => {
    let newDoc = iframe.contentDocument;
    if (newDoc == oldDoc) return;

    alert("New document is here!");

    clearInterval(timer); // cancel setInterval, don't need it any more
  }, 100);
</script>