js iframe获取documen中的对象为空问题

首先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后再获取就可以正常获取到对象了


 

  • 10
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 14
    评论
评论 14
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

豆趣编程

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值