先引用一段話:
window.name 傳輸技術,原本是 Thomas Frank 用於解決 cookie 的一些劣勢(每個域名 4 x 20 Kb的限制、數據只能是字符串、設置和獲取 cookie 語法的複雜等等)而發明的。後來 Kris Zyp 在此方法的基礎上強化了 window.name 傳輸 ,用來解決跨域數據傳輸問題。
window.name 的美妙之處:name值在不同的頁面(甚至不同域名)加載後依舊存在,並且可以支持非常長的 name 值(2MB)。
window.name 傳輸技術的基本原理:
當在瀏覽器中打開一個頁面,或者在頁面中添加一個iframe時即會創建一個對應的window對象,當頁面加載另一個新的頁面時,window的name屬性是不會變的。這樣就可以利用在頁面動態添加一個iframe然後src加載數據頁面,在數據頁面將需要的數據賦值給window.name。然而此時承載iframe的parent頁面還是不能直接訪問,不在同一域下iframe的name屬性,這時只需要將iframe再加載一個與承載頁面同域的空白頁面,即可對window.name進行數據讀取
示例:
www.test.com下a.html頁:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<button>click!</button>
<script type="text/javascript">
var a=document.getElementsByTagName("button")[0];
a.onclick=function(){ //button添加click事件
var inf=document.createElement("iframe"); //創建iframe
inf.src="http://www.domain.com/window.name/b.html"+"?h=5" //加載數據頁www.domain.com/window.name/b.html同事攜帶參數h=5
var body=document.getElementsByTagName("body")[0];
body.appendChild(inf); //引入a頁面
inf.onload=function(){
inf.src='http://www.test.com/b.html' //iframe加載完成,加載www.test.com域下邊的空白頁b.html
console.log(inf.contentWindow.name) //輸出window.name中的數據
body.removeChild(inf) //清除iframe
}
}
</script>
</body>
</html>
www.domain.com下b.html頁:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<a href="" target="" title="">2</a>
<script type="text/javascript" src="../cross/jquery-2.2.3.js">
</script>
<script>
var str=window.location.href.substr(-1,1); //獲取url中攜帶的參數值
$.ajax({
type:"get",
url:"http://www.domain.com/a.php"+"?m="+str, //通過ajax將查詢參數傳給php頁面
async:true,
success:function(res){
window.name=res //將接收到的查詢數據賦值給window.name
},
error:function(){
window.name='error' //..
}
});
</script>
</body>
</html>
在www.test.com下a頁面點擊button,完美跨域獲取到了www.domain.com下b頁面通過ajax請求從a.php得來的數據。
結束!