在带有部分标记的 iframe 内呈现时无法遍历 DOM

Failed to traverse DOM while rendered inside iframe with section tags

我面临无法遍历 iframe 中的 dom 的情况。我的代码如下。当我尝试访问 body 标签的 childNodes 时,控制台将显示 body 标签内没有 childNodes

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <iframe id="container"
        src="./resources/c07.xhtml"
        frameborder="0"></iframe>
    <style>
        #container {
            width: 100%;
            height: 800px;
        }
    </style>
    <script src="index.js"></script>
</body>
</html>

c07.xhtml

<!DOCTYPE html>
<html>
<body>

<h1>The section element</h1>

<section>
  <h2>History</h2>
  <p>The World Wide Fund for Nature (WWF)</p>
</section>

<section>
  <h2>Symbol</h2>
  <p>The Panda has become the symbol of WWF.</p>
</section>

</body>
</html>

//index.js

const parentNode = document.querySelector("#container");
const iframeBody =  iframeRef(parentNode);
console.log(element.childNodes[0].getElementsByTagName('section')); //prints HTMLCollection[] and length is 0

function iframeRef( frameRef ) {
    return frameRef.contentWindow
        ? frameRef.contentWindow.document
        : frameRef.contentDocument
}

我该如何解决这个问题?

试试这个对我有用。访问 setTimeout 函数内的 iframe dom 元素。

const parentNode = document.querySelector("#container");
setTimeout(() => {
  const iframWindow = parentNode.contentDocument;
  console.log(iframWindow.getElementsByTagName("section")); //prints HTMLCollection[] and length is 0
}, 1000);