通过 iframeElement.contentDocument.body 访问的 iframe 主体是一个空节点

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

我在开发服务器上有一个非常简单的设置(两个页面都在我的本地测试服务器上localhost:5500),我有一个主页

<!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>

和嵌套页面

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

当我在浏览器中加载主页时,写入控制台的输出是:<body></body> 我可以使用 iframe.contentDocument.getElementById('hello') 访问元素 #hello 但我想要 body 元素包括子元素。谁能给我解释一下为什么会这样

您必须等到 iframe 完全加载才能访问它的主体。

var iframe = document.getElementById('frame');

iframe.onload = function () {
    console.log(iframe.contentDocument.body);
}