Search code examples
javascripthtmliframesame-origin-policy

Iframe body when accessed through iframeElement.contentDocument.body is an empty node


I have a very simple setup on a dev server (both pages are on my local test server localhost:5500) where I have a main page

<!DOCTYPE html>
<html lang="en">
<head>
  <title>Example Mockup</title>
</head>
<body>
  <iframe src="./nested.html" id="frame"></iframe>
  <script>
    var iframe = document.getElementById('frame');
    console.log(iframe.contentDocument.body);
  </script>
</body>
</html>

and a nested page

<html>
    <body>
        <div id="hello">Hello, World</div>
    </body>
</html>

when I load the main page in my browser the output written to console is: <body></body> I can access the element #hello using iframe.contentDocument.getElementById('hello') but I want the body element including child elements. Can anyone please explain to me why is this happening


Solution

  • You have to wait until iframe loaded completely to access it's body.

    var iframe = document.getElementById('frame');
    
    iframe.onload = function () {
        console.log(iframe.contentDocument.body);
    }