使用windows.name解决js跨域数据通信
生活随笔
收集整理的這篇文章主要介紹了
使用windows.name解决js跨域数据通信
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
下面是參考文獻[1]的一個實踐驗證,測試環境略有修改,記錄如下:
測試場景:從網站A中的網頁去獲取網站B中網頁的數據
下面以news.sina.com.cn和news.163.com這兩個站點為例,將如下網頁都放到Nginx服務器根目錄下面的子目錄taoyx-test下面:
PageA.html內容如下:
<!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>跨域獲取數據</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內容如下:
<!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內容如下:
<!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 = '需要跨域傳遞的數據: cross-domain data,======= 雪峰流云!========';
</script>
</body>
</html>
為了創造兩個域名的環境,可以在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 是必須的。內容可為空。
2.iframe的onload事件綁定 必須這樣寫:
if(iframe.attachEvent){
? ? ?iframe.attachEvent('onload', loadfn);
} else {
? ? ?iframe.onload = loadfn;
}
3.調用domainData函數必須在body后面,或頁面加載完后。調用時會執行 http://news.163.com/taoyx-test/PageB.html 頁面的腳本。
參考文獻
[1].http://www.cnblogs.com/zjfree/archive/2011/02/24/1963591.html
總結
以上是生活随笔為你收集整理的使用windows.name解决js跨域数据通信的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 数字广告领域的若干专业词汇汇总
- 下一篇: 扩展typeof来判断js变量的类型