Fr3*_*Dev 1 html javascript iframe same-origin-policy
我在开发服务器上有一个非常简单的设置(两个页面都在我的本地测试服务器上localhost:5500),其中我有一个主页
<!DOCTYPE html>
<html lang="en">
<head>
<title>Example Mockup</title>
</head>
<body>
<iframe src="./nested.html" id="frame"></iframe>
<script>
var iframe = document.getElementById('frame');
console.log(iframe.contentDocument.body);
</script>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
和一个嵌套页面
<html>
<body>
<div id="hello">Hello, World</div>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
当我在浏览器中加载主页时,写入控制台的输出是:我可以使用<body></body>
访问该元素,但我想要包含子元素的 body 元素。谁能向我解释为什么会发生这种情况#helloiframe.contentDocument.getElementById('hello')
您必须等到 iframe 完全加载才能访问它的主体。
var iframe = document.getElementById('frame');
iframe.onload = function () {
console.log(iframe.contentDocument.body);
}
Run Code Online (Sandbox Code Playgroud)