localhost | 127.0.0.1 混用导致 iframe 获取 contentWindow 不正确问题

114 阅读1分钟

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在跑这个服务,加载时有如下请求

image.png

请求到的 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 这个属性

image.png

更换一下 iframe src 的写法后,就可以拿到正确的 window 了。如下:

<iframe src="http://127.0.0.1:6324/page_frame/" frameborder="0"></iframe>
<!-- 或者 -->
<iframe src="/page_frame/" frameborder="0"></iframe>

image.png

参考 MDN 文档 (得是英文文档,中文文档中没有这句话。

Access to the Window returned by contentWindow is subject to the rules defined by the same-origin policy

image.png

image.png

结论:可以看到 iframe 是有同源限制的。localhost127.0.0.1通常都是等效的,但是在这里获取到的window不一样。