【原理1】:window对象的name属性特征 —— name 属性可设置或返回存放窗口的名称的一个字符串,同一个浏览器窗口或同一个 iframe 载入的页面共享一个window.name。
意思是只要你不关闭页面,仅仅改变网址的话, window.name 是不会变的,而且每一个打开的页面都能获取并修改 window.name 的值。
【原理2】:父页面能够通过 iframe 的 contentWindow 的属性,访问到子页面的内容(不跨域的情况下)。
意思是利用 iframeObj.contentWindow.name 是能够获取到 iframe 窗口内同一域名页面的 window.name。
So,利用这两个特性,跨域方案如下:
案例:www.aaa.com/index.html 想要获取到 www.bbb.com/data.html 的数据。(辅助页面 www.aaa.com/null.html)
这三个页面,内容如下:
1、www.aaa.com/index.html
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>window.name跨域</title>
</head>
<body >
<iframe id="proxy" src="http://www.bbb.com/data.html" style="display: none;" onload="getData()"></iframe>
<script>
function getData(){
var iframe = document.getElementById('proxy');
iframe.onload = function(){ //覆盖掉载入时绑定的getData()函数
var data = iframe.contentWindow.name;
console.log(data); //data即为跨域获取到的window.name数据;
}
iframe.src = 'http://www.aaa.com/null.html';
}
</script>
</body>
</html>2、www.aaa.com/null.html
空页面,和 index.html 在同一域名下,为了让父页面能取到 iframe 的 window.name 值而存在。
3、www.bbb.com/data.html
准备传给 index.html 数据存放在 window.name字符串中
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>数据</title>
</head>
<body >
<!-- 页面其他内容 -->
<script>
window.name = "somedata";//数据
</script>
</body>
</html>
127




被折叠的 条评论
为什么被折叠?



