js通过iframe访问跨域网站,获取不到内部标签?

1.页面iframe访问跨域网站baidu
html
<iframe id="iframe" src="http://www.baidu.com" frameborder="0"></iframe>
javascript
let iframe = document.getElementById('iframe')
2.打印访问内容

1.查看是否可以访问document

console.log(iframe.contentWindow.document) //结果如下图:可以访问

在这里插入图片描述

2.查看是否可以访问到html标签

//方式1
console.log(iframe.contentWindow.document.html) // undefined
//方式2
console.log(iframe.contentWindow.document.childNodes[0]) //可以访问

在这里插入图片描述
3.通过childNodes是否可以继续访问下一级

console.log(iframe.contentWindow.document.childNodes[0].childNodes); //此处可以获取到类数组,如下图
获取具体head和body标签时,谷歌undefined ,但是火狐可以,再继续childNodes的话就[]了
console.log(iframe.contentWindow.document.childNodes[0].childNodes[0]) //undefined
console.log(iframe.contentWindow.document.childNodes[0].childNodes[1])

在这里插入图片描述在这里插入图片描述

3.总结

通过iframe访问跨域网站时,
1.直接访问标签的话,只允许访问到document
2.通过childNodes的话,谷歌可以查看html.childNodes,火狐可以查看到head和body标签

猜你喜欢

转载自blog.csdn.net/m0_37285193/article/details/115694090