日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 人文社科 > 生活经验 >内容正文

生活经验

使用windows.name解决js跨域数据通信

發布時間:2023/11/27 生活经验 31 豆豆
生活随笔 收集整理的這篇文章主要介紹了 使用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跨域数据通信的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。