Me enfrento a una situación en la que no puedo atravesar el dom dentro del iframe. Mi código es el siguiente. Cuando intento acceder a childNodes de la etiqueta del body , la consola mostrará que no hay childNodes dentro de la etiqueta del cuerpo.
<!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 }¿Cómo puedo resolver esto?
Prueba esto, me funciona. Acceda a los elementos iframe dom dentro de la función setTimeout .
const parentNode = document.querySelector("#container"); setTimeout(() => { const iframWindow = parentNode.contentDocument; console.log(iframWindow.getElementsByTagName("section")); //prints HTMLCollection[] and length is 0 }, 1000);