Access to innerHTML of iframe



我试图访问iframe的内部HTML,其中iframe的源位于同一域。何时使用

var pageSource = document.getElementById('iframeID');

并在浏览器中使用inspect,我可以看到contentDocument.body.innerHTML具有我试图抓取的值。然而,如果我试图在代码中访问这些值,它是空的:

<!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在这种情况下是不正确的。

我试过Chrome、Edge和Firefox。这似乎是浏览器正在做的事情。它阻塞了访问吗?明明知道里面有东西,为什么还是空的?

对于那些会质疑我为什么这样做的人,另一个页面只是一个测试页面,以获得此工作。我打算用一个被代理的页面来替换它,以便从外部站点获取源。

多亏了Ourborus,这是可行的:

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

最新更新