原文鏈接:http://blog.csdn.net/joyhen/article/details/21631833
1.同源策略如下:
URL | 說明 | 是否允許通信 |
---|---|---|
http://www.a.com/a.js http://www.a.com/b.js |
同一域名下 | 允許 |
http://www.a.com/lab/a.js http://www.a.com/script/b.js |
同一域名下不同文件夾 | 允許 |
http://www.a.com:8000/a.js http://www.a.com/b.js |
同一域名,不同端口 | 不允許 |
http://www.a.com/a.js https://www.a.com/b.js |
同一域名,不同協議 | 不允許 |
http://www.a.com/a.js http://70.32.92.74/b.js |
域名和域名對應ip | 不允許 |
http://www.a.com/a.js http://script.a.com/b.js |
主域相同,子域不同 | 不允許 |
http://www.a.com/a.js http://a.com/b.js |
同一域名,不同二級域名(同上) | 不允許(cookie這種情況下也不允許訪問) |
http://www.cnblogs.com/a.js http://www.a.com/b.js |
不同域名 | 不允許 |
特別注意兩點:
第一,如果是協議和端口造成的跨域問題“前台”是無能為力的,
第二:在跨域問題上,域僅僅是通過“URL的首部”來識別而不會去嘗試判斷相同的ip地址對應着兩個域或兩個域是否在同一個ip上。
“URL的首部”指window.location.protocol +window.location.host,也可以理解為“Domains, protocols and ports must match”。
2. 前端解決跨域問題
1> document.domain + iframe (只有在主域相同的時候才能使用該方法)
1) 在www.a.com/a.html中:
1
2
3
4
5
6
7
8
9
10
|
document.domain =
'a.com'
;
var
ifr = document.createElement(
'iframe'
);
ifr.display = none;
document.body.appendChild(ifr);
ifr.onload =
function
(){
var
doc = ifr.contentDocument || ifr.contentWindow.document;
//在這里操作doc,也就是b.html
ifr.onload =
null
;
};
|
2) 在www.script.a.com/b.html中:
1
|
document.domain =
'a.com'
;
|
2> 動態創建script
這個沒什么好說的,因為script標簽不受同源策略的限制。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
function
loadScript(url, func) {
var
head = document.head || document.getElementByTagName(
'head'
)[0];
var
script = document.createElement(
'script'
);
script.src = url;
script.onload = script.onreadystatechange =
function
(){
if
(!
this
.readyState ||
this
.readyState==
'loaded'
||
this
.readyState==
'complete'
){
func();
script.onload = script.onreadystatechange =
null
;
}
};
head.insertBefore(script, 0);
}
window.baidu = {
sug:
function
(data){
console.log(data);
}
}
//我們請求的內容在哪里?
//我們可以在chorme調試面板的source中看到script引入的內容
|
3> location.hash + iframe
原理是利用location.hash來進行傳值。
假設域名a.com下的文件cs1.html要和cnblogs.com域名下的cs2.html傳遞信息。
1) cs1.html首先創建自動創建一個隱藏的iframe,iframe的src指向cnblogs.com域名下的cs2.html頁面
2) cs2.html響應請求后再將通過修改cs1.html的hash值來傳遞數據
3) 同時在cs1.html上加一個定時器,隔一段時間來判斷location.hash的值有沒有變化,一旦有變化則獲取獲取hash值
注:由於兩個頁面不在同一個域下IE、Chrome不允許修改parent.location.hash的值,所以要借助於a.com域名下的一個代理iframe
代碼如下:
先是a.com下的文件cs1.html文件:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
function
startRequest(){
var
ifr = document.createElement(
'iframe'
);
ifr.style.display =
'none'
;
document.body.appendChild(ifr);
}
function
checkHash() {
try
{
var
data = location.hash ? location.hash.substring(1) :
''
;
if
(console.log) {
console.log(
'Now the data is '
+data);
}
}
catch
(e) {};
}
setInterval(checkHash, 2000);
|
cnblogs.com域名下的cs2.html:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
//模擬一個簡單的參數處理操作
switch
(location.hash){
case
'#paramdo'
:
callBack();
break
;
case
'#paramset'
:
//do something……
break
;
}
function
callBack(){
try
{
parent.location.hash =
'somedata'
;
}
catch
(e) {
// ie、chrome的安全機制無法修改parent.location.hash,
// 所以要利用一個中間的cnblogs域下的代理iframe
var
ifrproxy = document.createElement(
'iframe'
);
ifrproxy.style.display =
'none'
;
document.body.appendChild(ifrproxy);
}
}
|
a.com下的域名cs3.html
1
2
|
//因為parent.parent和自身屬於同一個域,所以可以改變其location.hash的值
parent.parent.location.hash = self.location.hash.substring(1);
|
4> window.name + iframe
window.name 的美妙之處:name 值在不同的頁面(甚至不同域名)加載后依舊存在,並且可以支持非常長的 name 值(2MB)。
1) 創建a.com/cs1.html
2) 創建a.com/proxy.html,並加入如下代碼
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
|
<head>
<script>
function
proxy(url, func){
var
isFirst =
true
,
ifr = document.createElement(
'iframe'
),
loadFunc =
function
(){
if
(isFirst){
isFirst =
false
;
}
else
{
func(ifr.contentWindow.name);
ifr.contentWindow.close();
document.body.removeChild(ifr);
ifr.src =
''
;
ifr =
null
;
}
};
ifr.src = url;
ifr.style.display =
'none'
;
if
(ifr.attachEvent) ifr.attachEvent(
'onload'
, loadFunc);
else
ifr.onload = loadFunc;
document.body.appendChild(iframe);
}
</script>
</head>
<body>
<script>
console.log(data);
});
</script>
</body>
|
3 在b.com/cs1.html中包含:
1
2
3
|
<script>
window.name =
'要傳送的內容'
;
</script>
|
5> postMessage(HTML5中的XMLHttpRequest Level 2中的API)
1) a.com/index.html中的代碼:
1
2
3
4
5
6
7
8
9
|
<iframe id=
"ifr"
src=
"b.com/index.html"
></iframe>
<script type=
"text/javascript"
>
window.onload =
function
() {
var
ifr = document.getElementById(
'ifr'
);
// 若寫成'http://c.com'就不會執行postMessage了
ifr.contentWindow.postMessage(
'I was there!'
, targetOrigin);
};
</script>
|
2) b.com/index.html中的代碼:
1
2
3
4
5
6
7
8
9
10
|
<script type=
"text/javascript"
>
window.addEventListener(
'message'
,
function
(event){
// 通過origin屬性判斷消息來源地址
alert(event.data);
// 彈出"I was there!"
alert(event.source);
// 對a.com、index.html中window對象的引用
// 但由於同源策略,這里event.source不可以訪問window對象
}
},
false
);
</script>
|
6> CORS
CORS背后的思想,就是使用自定義的HTTP頭部讓瀏覽器與服務器進行溝通,從而決定請求或響應是應該成功,還是應該失敗。
IE中對CORS的實現是xdr
1
2
3
4
5
6
7
|
var
xdr =
new
XDomainRequest();
xdr.onload =
function
(){
console.log(xdr.responseText);
}
......
xdr.send(
null
);
|
其它瀏覽器中的實現就在xhr中
1
2
3
4
5
6
7
8
9
10
11
|
var
xhr =
new
XMLHttpRequest();
xhr.onreadystatechange =
function
() {
if
(xhr.readyState == 4){
if
(xhr.status >= 200 && xhr.status < 304 || xhr.status == 304){
console.log(xhr.responseText);
}
}
}
......
xhr.send(
null
);
|
實現跨瀏覽器的CORS
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
function
createCORS(method, url){
var
xhr =
new
XMLHttpRequest();
if
(
'withCredentials'
in
xhr){
xhr.open(method, url,
true
);
}
else
if
(
typeof
XDomainRequest !=
'undefined'
){
var
xhr =
new
XDomainRequest();
xhr.open(method, url);
}
else
{
xhr =
null
;
}
return
xhr;
}
if
(request){
request.onload =
function
(){
......
};
request.send();
}
|
7> JSONP
JSONP包含兩部分:回調函數和數據。
回調函數是當響應到來時要放在當前頁面被調用的函數。
數據就是傳入回調函數中的json數據,也就是回調函數的參數了。
1
2
3
4
5
6
7
8
9
10
11
12
13
|
function
handleResponse(response){
console.log(
'The responsed data is: '
+response.data);
}
var
script = document.createElement(
'script'
);
document.body.insertBefore(script, document.body.firstChild);
/*handleResonse({"data": "zhe"})*/
//原理如下:
//當我們通過script標簽請求時
//后台就會根據相應的參數(json,handleResponse)
//來生成相應的json數據(handleResponse({"data": "zhe"}))
//最后這個返回的json數據(代碼)就會被放在當前js文件中被執行
//至此跨域通信完成
|
jsonp雖然很簡單,但是有如下缺點:
1)安全問題(請求代碼中可能存在安全隱患)
2)要確定jsonp請求是否失敗並不容易
8> web sockets
web sockets是一種瀏覽器的API,它的目標是在一個單獨的持久連接上提供全雙工、雙向通信。(同源策略對web sockets不適用)
web sockets原理:在JS創建了web socket之后,會有一個HTTP請求發送到瀏覽器以發起連接。取得服務器響應后,建立的連接會使用HTTP升級從HTTP協議交換為web sockt協議。
只有在支持web socket協議的服務器上才能正常工作。
1
2
3
4
5
|
socket.send(
'hello WebSockt'
);
socket.onmessage =
function
(event){
var
data = event.data;
}
|
1.同源策略如下:
URL | 說明 | 是否允許通信 |
---|---|---|
http://www.a.com/a.js http://www.a.com/b.js |
同一域名下 | 允許 |
http://www.a.com/lab/a.js http://www.a.com/script/b.js |
同一域名下不同文件夾 | 允許 |
http://www.a.com:8000/a.js http://www.a.com/b.js |
同一域名,不同端口 | 不允許 |
http://www.a.com/a.js https://www.a.com/b.js |
同一域名,不同協議 | 不允許 |
http://www.a.com/a.js http://70.32.92.74/b.js |
域名和域名對應ip | 不允許 |
http://www.a.com/a.js http://script.a.com/b.js |
主域相同,子域不同 | 不允許 |
http://www.a.com/a.js http://a.com/b.js |
同一域名,不同二級域名(同上) | 不允許(cookie這種情況下也不允許訪問) |
http://www.cnblogs.com/a.js http://www.a.com/b.js |
不同域名 | 不允許 |
特別注意兩點:
第一,如果是協議和端口造成的跨域問題“前台”是無能為力的,
第二:在跨域問題上,域僅僅是通過“URL的首部”來識別而不會去嘗試判斷相同的ip地址對應着兩個域或兩個域是否在同一個ip上。
“URL的首部”指window.location.protocol +window.location.host,也可以理解為“Domains, protocols and ports must match”。
2. 前端解決跨域問題
1> document.domain + iframe (只有在主域相同的時候才能使用該方法)
1) 在www.a.com/a.html中:
1
2
3
4
5
6
7
8
9
10
|
document.domain =
'a.com'
;
var
ifr = document.createElement(
'iframe'
);
ifr.display = none;
document.body.appendChild(ifr);
ifr.onload =
function
(){
var
doc = ifr.contentDocument || ifr.contentWindow.document;
//在這里操作doc,也就是b.html
ifr.onload =
null
;
};
|
2) 在www.script.a.com/b.html中:
1
|
document.domain =
'a.com'
;
|
2> 動態創建script
這個沒什么好說的,因為script標簽不受同源策略的限制。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
function
loadScript(url, func) {
var
head = document.head || document.getElementByTagName(
'head'
)[0];
var
script = document.createElement(
'script'
);
script.src = url;
script.onload = script.onreadystatechange =
function
(){
if
(!
this
.readyState ||
this
.readyState==
'loaded'
||
this
.readyState==
'complete'
){
func();
script.onload = script.onreadystatechange =
null
;
}
};
head.insertBefore(script, 0);
}
window.baidu = {
sug:
function
(data){
console.log(data);
}
}
//我們請求的內容在哪里?
//我們可以在chorme調試面板的source中看到script引入的內容
|
3> location.hash + iframe
原理是利用location.hash來進行傳值。
假設域名a.com下的文件cs1.html要和cnblogs.com域名下的cs2.html傳遞信息。
1) cs1.html首先創建自動創建一個隱藏的iframe,iframe的src指向cnblogs.com域名下的cs2.html頁面
2) cs2.html響應請求后再將通過修改cs1.html的hash值來傳遞數據
3) 同時在cs1.html上加一個定時器,隔一段時間來判斷location.hash的值有沒有變化,一旦有變化則獲取獲取hash值
注:由於兩個頁面不在同一個域下IE、Chrome不允許修改parent.location.hash的值,所以要借助於a.com域名下的一個代理iframe
代碼如下:
先是a.com下的文件cs1.html文件:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
function
startRequest(){
var
ifr = document.createElement(
'iframe'
);
ifr.style.display =
'none'
;
document.body.appendChild(ifr);
}
function
checkHash() {
try
{
var
data = location.hash ? location.hash.substring(1) :
''
;
if
(console.log) {
console.log(
'Now the data is '
+data);
}
}
catch
(e) {};
}
setInterval(checkHash, 2000);
|
cnblogs.com域名下的cs2.html:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
//模擬一個簡單的參數處理操作
switch
(location.hash){
case
'#paramdo'
:
callBack();
break
;
case
'#paramset'
:
//do something……
break
;
}
function
callBack(){
try
{
parent.location.hash =
'somedata'
;
}
catch
(e) {
// ie、chrome的安全機制無法修改parent.location.hash,
// 所以要利用一個中間的cnblogs域下的代理iframe
var
ifrproxy = document.createElement(
'iframe'
);
ifrproxy.style.display =
'none'
;
document.body.appendChild(ifrproxy);
}
}
|
a.com下的域名cs3.html
1
2
|
//因為parent.parent和自身屬於同一個域,所以可以改變其location.hash的值
parent.parent.location.hash = self.location.hash.substring(1);
|
4> window.name + iframe
window.name 的美妙之處:name 值在不同的頁面(甚至不同域名)加載后依舊存在,並且可以支持非常長的 name 值(2MB)。
1) 創建a.com/cs1.html
2) 創建a.com/proxy.html,並加入如下代碼
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
|
<head>
<script>
function
proxy(url, func){
var
isFirst =
true
,
ifr = document.createElement(
'iframe'
),
loadFunc =
function
(){
if
(isFirst){
isFirst =
false
;
}
else
{
func(ifr.contentWindow.name);
ifr.contentWindow.close();
document.body.removeChild(ifr);
ifr.src =
''
;
ifr =
null
;
}
};
ifr.src = url;
ifr.style.display =
'none'
;
if
(ifr.attachEvent) ifr.attachEvent(
'onload'
, loadFunc);
else
ifr.onload = loadFunc;
document.body.appendChild(iframe);
}
</script>
</head>
<body>
<script>
console.log(data);
});
</script>
</body>
|
3 在b.com/cs1.html中包含:
1
2
3
|
<script>
window.name =
'要傳送的內容'
;
</script>
|
5> postMessage(HTML5中的XMLHttpRequest Level 2中的API)
1) a.com/index.html中的代碼:
1
2
3
4
5
6
7
8
9
|
<iframe id=
"ifr"
src=
"b.com/index.html"
></iframe>
<script type=
"text/javascript"
>
window.onload =
function
() {
var
ifr = document.getElementById(
'ifr'
);
// 若寫成'http://c.com'就不會執行postMessage了
ifr.contentWindow.postMessage(
'I was there!'
, targetOrigin);
};
</script>
|
2) b.com/index.html中的代碼:
1
2
3
4
5
6
7
8
9
10
|
<script type=
"text/javascript"
>
window.addEventListener(
'message'
,
function
(event){
// 通過origin屬性判斷消息來源地址
alert(event.data);
// 彈出"I was there!"
alert(event.source);
// 對a.com、index.html中window對象的引用
// 但由於同源策略,這里event.source不可以訪問window對象
}
},
false
);
</script>
|
6> CORS
CORS背后的思想,就是使用自定義的HTTP頭部讓瀏覽器與服務器進行溝通,從而決定請求或響應是應該成功,還是應該失敗。
IE中對CORS的實現是xdr
1
2
3
4
5
6
7
|
var
xdr =
new
XDomainRequest();
xdr.onload =
function
(){
console.log(xdr.responseText);
}
......
xdr.send(
null
);
|
其它瀏覽器中的實現就在xhr中
1
2
3
4
5
6
7
8
9
10
11
|
var
xhr =
new
XMLHttpRequest();
xhr.onreadystatechange =
function
() {
if
(xhr.readyState == 4){
if
(xhr.status >= 200 && xhr.status < 304 || xhr.status == 304){
console.log(xhr.responseText);
}
}
}
......
xhr.send(
null
);
|
實現跨瀏覽器的CORS
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
function
createCORS(method, url){
var
xhr =
new
XMLHttpRequest();
if
(
'withCredentials'
in
xhr){
xhr.open(method, url,
true
);
}
else
if
(
typeof
XDomainRequest !=
'undefined'
){
var
xhr =
new
XDomainRequest();
xhr.open(method, url);
}
else
{
xhr =
null
;
}
return
xhr;
}
if
(request){
request.onload =
function
(){
......
};
request.send();
}
|
7> JSONP
JSONP包含兩部分:回調函數和數據。
回調函數是當響應到來時要放在當前頁面被調用的函數。
數據就是傳入回調函數中的json數據,也就是回調函數的參數了。
1
2
3
4
5
6
7
8
9
10
11
12
13
|
function
handleResponse(response){
console.log(
'The responsed data is: '
+response.data);
}
var
script = document.createElement(
'script'
);
document.body.insertBefore(script, document.body.firstChild);
/*handleResonse({"data": "zhe"})*/
//原理如下:
//當我們通過script標簽請求時
//后台就會根據相應的參數(json,handleResponse)
//來生成相應的json數據(handleResponse({"data": "zhe"}))
//最后這個返回的json數據(代碼)就會被放在當前js文件中被執行
//至此跨域通信完成
|
jsonp雖然很簡單,但是有如下缺點:
1)安全問題(請求代碼中可能存在安全隱患)
2)要確定jsonp請求是否失敗並不容易
8> web sockets
web sockets是一種瀏覽器的API,它的目標是在一個單獨的持久連接上提供全雙工、雙向通信。(同源策略對web sockets不適用)
web sockets原理:在JS創建了web socket之后,會有一個HTTP請求發送到瀏覽器以發起連接。取得服務器響應后,建立的連接會使用HTTP升級從HTTP協議交換為web sockt協議。
只有在支持web socket協議的服務器上才能正常工作。
1
2
3
4
5
|
socket.send(
'hello WebSockt'
);
socket.onmessage =
function
(event){
var
data = event.data;
}
|