I am trying to access the inner HTML of an iframe, where the source for the iframe is in the same domain. When is use
var pageSource = document.getElementById('iframeID');
and use inspect in the browser, I can see that contentDocument.body.innerHTML has the values I'm trying to grab. However, if I try to access those values in the code, it's empty:
<!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 is not correct in this case.
I've tried Chrome, Edge and Firefox. It appears to be something that the browser is doing. Is it blocking access? Why is this empty when I know there is something there?
For those who would question why I am doing this, the other page is just a test page to get this working. I intend to replace that with a page that is proxied, order to grab the source from an external site.
Thanks to Ourborus, this works:
<!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>