首先src为同源的话,父window是可以获取iframe中的元素对象的。
通过iframe获取window、document
如果想获取iframe里的window或者document,可以使用
iframe.contentWindow、iframe.contentDocument
iframe.contentDocument=iframe.contentWindow.document,不过iframe.contentDocument在IE8及以下的版本不支持。
或者使用window.frames[0]/window.frames['name']先或者frame的window对象,再用window.frames[0].document的方法获取frame的document对象
然后获取iframe中元素是这样:
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style type="text/css">
iframe{
width:100%;height:800px;
}
</style>
</head>
<body>
<iframe src="http://192.168.100.150:8020/实验/jsonp.html" frameborder="0" id="iframe"></iframe>
<script type="text/javascript">
var i=document.getElementById("iframe");
console.log(i.contentWindow.document.getElementById("text").innerHTML)
//或者
console.log(i.contentDocument.getElementById("text").innerHTML)
</script>
</body>
</html>
但我试了一下,结果获取不到,报错iframe1.html?__hbt=1544149649954:16 Uncaught TypeError: Cannot read property 'innerHTML' of null at...
获取到的document中只有head和body
console.log(i.contentWindow.document)
解决办法:
原因其实是iframe加载是需要时间的,它还没加载完我就在js中直接获取对象了,所以获取为空
var i=document.getElementById("iframe");
i.onload=function(){
console.log(i.contentDocument)
console.log(i.contentWindow.document.getElementById("text").innerHTML)
}
让iframe加载完onload后再获取就可以正常获取到对象了