Estoy tratando de acceder al HTML interno de un iframe, donde la fuente del iframe está en el mismo dominio. cuando se usa
var pageSource = document.getElementById('iframeID'); y uso inspeccionar en el navegador, puedo ver que contentDocument.body.innerHTML tiene los valores que estoy tratando de obtener. Sin embargo, si trato de acceder a esos valores en el código, está vacío:
<!DOCTYPE html> <html lang="en-US"> <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>Test Stuff</title> </head> <body> <div height=100 >This is a page:</div> <div height=1600 > <iframe name="iframeID" id="iframeID" width=1500 height=800 src="https://same.domain.asparent/otherpage"></iframe> </div> <div height=200><p id="sourceOut">Page source here.</p></div> <script> var pageSource = document.getElementById('iframeID').contentDocument.body.innerHTML; document.getElementById("sourceOut").innerHTML = pageSource; console.log(pageSource); </script> </body> </html> document.getElementById('iframeID').document.body.innerHTML no es correcto en este caso.
He probado Chrome, Edge y Firefox. Parece ser algo que el navegador está haciendo. ¿Está bloqueando el acceso? ¿Por qué está vacío cuando sé que hay algo allí?
Para aquellos que se pregunten por qué estoy haciendo esto, la otra página es solo una página de prueba para que funcione. Tengo la intención de reemplazar eso con una página que es proxy, para obtener la fuente de un sitio externo.
Gracias a Ourborus, esto funciona:
<!DOCTYPE html> <html lang="en-US"> <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>Test Stuff</title> </head> <body> <div height=100 >This is a page:</div> <div height=1600 > <iframe name="iframeID" id="iframeID" width=1500 height=800 src="https://same.domain.here/otherpage"></iframe> </div> <div height=200><p id="sourceOut">Page source here.</p></div> <script> function sleep(ms) { return new Promise(resolve => setTimeout(resolve, ms)); } async function getSource(){ await sleep(1000); var pageSource = document.getElementById('iframeID').contentDocument.body.innerHTML; document.getElementById("sourceOut").innerHTML = pageSource; console.log(pageSource); } getSource(); </script> </body> </html>