iframe 示例如下
<iframe src="http://localhost:6324/page_frame/" frameborder="0"></iframe>
对应获取 iframe window 的方法
console.log('iframeWindow ', document.getElementsByTagName('iframe')[0].contentWindow)
此时,我是本地http://127.0.0.1:6324在跑这个服务,加载时有如下请求
请求到的 html 文件就是这个,我给 window 上挂了一个属性 aaa
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>page_frame</title>
</head>
<body></body>
<script>
window.aaa = 1
</script>
</html>
能够拿到 window,但是发现并没有 aaa 这个属性
更换一下 iframe src 的写法后,就可以拿到正确的 window 了。如下:
<iframe src="http://127.0.0.1:6324/page_frame/" frameborder="0"></iframe>
<!-- 或者 -->
<iframe src="/page_frame/" frameborder="0"></iframe>
参考 MDN 文档 (得是英文文档,中文文档中没有这句话。)
Access to the
Windowreturned bycontentWindowis subject to the rules defined by the same-origin policy
结论:可以看到 iframe 是有同源限制的。localhost 和 127.0.0.1通常都是等效的,但是在这里获取到的window不一样。