使用windows.name解决js跨域数据通信
下面是參考文獻[1]的一個實踐驗證,測試環(huán)境略有修改,記錄如下:
測試場景:從網(wǎng)站A中的網(wǎng)頁去獲取網(wǎng)站B中網(wǎng)頁的數(shù)據(jù)
下面以news.sina.com.cn和news.163.com這兩個站點為例,將如下網(wǎng)頁都放到Nginx服務(wù)器根目錄下面的子目錄taoyx-test下面:
PageA.html內(nèi)容如下:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head><meta http-equiv="content-type" content="text/html; charset=utf-8"><title>跨域獲取數(shù)據(jù)</title><script type="text/javascript">function domainData(url, fn){var isFirst = true;var iframe = document.createElement('iframe');iframe.style.display = 'none';var loadfn = function(){if(isFirst){iframe.contentWindow.location = 'http://news.sina.com.cn/taoyx-test/PageNull.html';isFirst = false;} else {fn(iframe.contentWindow.name);iframe.contentWindow.document.write('');iframe.contentWindow.close();document.body.removeChild(iframe);iframe.src = '';iframe = null;}};iframe.src = url;if(iframe.attachEvent){iframe.attachEvent('onload', loadfn);} else {iframe.onload = loadfn;}document.body.appendChild(iframe);}</script>
</head>
<body></body><script type="text/javascript">domainData('http://news.163.com/taoyx-test/PageB.html', function(data){alert(data);});</script>
</html>
PageNull.html內(nèi)容如下:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<title>Windows.name變量測試</title>
<link rel="shortcut icon" href="http://t10.baidu.com/it/u=4094539827,178906815&fm=58" />
</head>
<body>
</body>
</html>
PageB.html內(nèi)容如下:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<title>Windows.name變量測試</title>
<link rel="shortcut icon" href="http://t10.baidu.com/it/u=4094539827,178906815&fm=58" />
</head>
<body>
<script>window.name = '需要跨域傳遞的數(shù)據(jù): cross-domain data,======= 雪峰流云!========';
</script>
</body>
</html>
為了創(chuàng)造兩個域名的環(huán)境,可以在hosts文件中添加如下域名:
10.10.110.149 ? news.sina.com.cn
10.10.110.149 ? news.163.com
在chrome中打開如下鏈接, http://news.sina.com.cn/taoyx-test/PageA.html 得到如下效果圖
注意事項:
1.PageNull.html 是必須的。內(nèi)容可為空。
2.iframe的onload事件綁定 必須這樣寫:
if(iframe.attachEvent){
? ? ?iframe.attachEvent('onload', loadfn);
} else {
? ? ?iframe.onload = loadfn;
}
3.調(diào)用domainData函數(shù)必須在body后面,或頁面加載完后。調(diào)用時會執(zhí)行 http://news.163.com/taoyx-test/PageB.html 頁面的腳本。
參考文獻
[1].http://www.cnblogs.com/zjfree/archive/2011/02/24/1963591.html
總結(jié)
以上是生活随笔為你收集整理的使用windows.name解决js跨域数据通信的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 数字广告领域的若干专业词汇汇总
- 下一篇: 扩展typeof来判断js变量的类型