第四期《前端跨域解決》
什麼是跨域?
跨域,指的是瀏覽器不能執行其他網站的指令碼。它是由瀏覽器的同源策略造成的,是瀏覽器對javascript施加的安全限制。
所謂同源是指,域名,協議,埠均相同,不明白沒關係,舉個栗子:
http://www.123.com/index.html
呼叫 http://www.123.com/server.php
(非跨域)
http://www.123.com/index.html
呼叫 http://www.456.com/server.php
(主域名不同:123/456,跨域)
http://abc.123.com/index.html
呼叫 http://def.123.com/server.php
(子域名不同:abc/def,跨域)
http://www.123.com:8080/index.html
呼叫 http://www.123.com:8081/server.php
(埠不同:8080/8081,跨域)
http://www.123.com/index.html
呼叫 https://www.123.com/server.php
(協議不同:http/https,跨域)
請注意:localhost和127.0.0.1雖然都指向本機,但也屬於跨域。
瀏覽器執行javascript指令碼時,會檢查這個指令碼屬於哪個頁面,如果不是同源頁面,就不會被執行。
特別注意兩點:
第一,如果是協議和埠造成的跨域問題“前臺”是無能為力的。
第二:在跨域問題上,域僅僅是通過“URL的首部”來識別而不會去嘗試判斷相同的ip地址對應著兩個域或兩個域是否在同一個ip上。
“URL的首部”指window.location.protocol +window.location.host
,也可以理解為“Domains,
protocols and ports must match
”。
前端解決跨域問題
1. document.domain + iframe (只有在主域相同的時候才能使用該方法)
在www.a.com/a.html
中:
document.domain = 'a.com'; var ifr = document.createElement('iframe'); ifr.src = 'http://www.script.a.com/b.html'; ifr.display = none; document.body.appendChild(ifr); ifr.onload = function(){ var doc = ifr.contentDocument || ifr.contentWindow.document; //在這裡操作doc,也就是b.html ifr.onload = null; };
在www.script.a.com/b.html
中:
document.domain = 'a.com';
2. location.hash + iframe
原理是利用location.hash來進行傳值。
假設域名a.com下的檔案cs1.html要和cnblogs.com域名下的cs2.html傳遞資訊。
-
cs1.html首先建立自動建立一個隱藏的iframe,iframe的src指向cnblogs.com域名下的cs2.html頁面
-
cs2.html響應請求後再將通過修改cs1.html的hash值來傳遞資料
-
同時在cs1.html上加一個定時器,隔一段時間來判斷location.hash的值有沒有變化,一旦有變化則獲取獲取hash值
注:由於兩個頁面不在同一個域下IE、Chrome不允許修改parent.location.hash的值,所以要藉助於a.com域名下的一個代理iframe
先是a.com下的檔案cs1.html檔案:
function startRequest(){
var ifr = document.createElement('iframe');
ifr.style.display = 'none';
ifr.src = 'http://www.cnblogs.com/lab/cscript/cs2.html#paramdo';
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:
//模擬一個簡單的引數處理操作
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';
// 注意該檔案在"a.com"域下
ifrproxy.src = 'http://a.com/test/cscript/cs3.html#somedata';
document.body.appendChild(ifrproxy);
}
}
a.com下的域名cs3.html
//因為parent.parent和自身屬於同一個域,所以可以改變其location.hash的值
parent.parent.location.hash = self.location.hash.substring(1);
3. window.name + iframe
window.name 的美妙之處:name 值在不同的頁面(甚至不同域名)載入後依舊存在,並且可以支援非常長的 name 值(2MB)。
-
建立a.com/cs1.html
-
建立a.com/proxy.html,並加入如下程式碼
<head>
<script>
function proxy(url, func) {
var isFirst = true,
ifr = document.createElement('iframe'),
loadFunc = function () {
if (isFirst) {
ifr.contentWindow.location = 'http://a.com/cs1.html';
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>
proxy('http://www.baidu.com/', function (data) {
console.log(data);
});
</script>
</body>
3 在b.com/cs1.html中包含:
<script>
window.name = '要傳送的內容';
</script>
4. postMessage(HTML5中的XMLHttpRequest Level 2中的API)
a.com/index.html中的程式碼:
<iframe id="ifr" src="b.com/index.html"></iframe>
<script type="text/javascript">
window.onload = function() {
var ifr = document.getElementById('ifr');
// 若寫成'http://b.com/c/proxy.html'效果一樣
var targetOrigin = 'http://b.com';
// 若寫成'http://c.com'就不會執行postMessage了
ifr.contentWindow.postMessage('I was there!', targetOrigin);
};
</script>
b.com/index.html中的程式碼:
<script type="text/javascript">
window.addEventListener('message', function(event){
// 通過origin屬性判斷訊息來源地址
if (event.origin == 'http://a.com') {
// 彈出"I was there!"
alert(event.data);
// 對a.com、index.html中window物件的引用
alert(event.source);
// 但由於同源策略,這裡event.source不可以訪問window物件
}
}, false);
</script>
5. JSONP
JSONP包含兩部分:回撥函式和資料。
回撥函式是當響應到來時要放在當前頁面被呼叫的函式。
資料就是傳入回撥函式中的json資料,也就是回撥函式的引數了。
function handleResponse(response){
console.log('The responsed data is: '+response.data);
}
var script = document.createElement('script');
script.src = 'http://www.baidu.com/json/?callback=handleResponse';
document.body.insertBefore(script, document.body.firstChild);
/*handleResonse({"data": "zhe"})*/
//原理如下:
//當我們通過script標籤請求時
//後臺就會根據相應的引數(json,handleResponse)
//來生成相應的json資料(handleResponse({"data": "zhe"}))
//最後這個返回的json資料(程式碼)就會被放在當前js檔案中被執行
//至此跨域通訊完成
jsonp雖然很簡單,但是有如下缺點:
1)安全問題(請求程式碼中可能存在安全隱患)
2)要確定jsonp請求是否失敗並不容易
- jsonp 只是get請求
6. web sockets
web sockets是一種瀏覽器的API,它的目標是在一個單獨的持久連線上提供全雙工、雙向通訊。(同源策略對web sockets不適用)
web sockets原理:在JS建立了web socket之後,會有一個HTTP請求傳送到瀏覽器以發起連線。取得伺服器響應後,建立的連線會使用HTTP升級從HTTP協議交換為web sockt協議。
只有在支援web socket協議的伺服器上才能正常工作。
//http->ws; https->wss
var socket = new WebSockt('ws://www.baidu.com');
socket.send('hello WebSockt');
socket.onmessage = function(event){
var data = event.data;
}
7. CORS
CORS背後的思想,就是使用自定義的HTTP頭部讓瀏覽器與伺服器進行溝通,從而決定請求或響應是應該成功,還是應該失敗。
IE中對CORS的實現是xdr
var xdr = new XDomainRequest();
xdr.onload = function(){
console.log(xdr.responseText);
}
xdr.open('get', 'http://www.baidu.com');
......
xdr.send(null);
其它瀏覽器中的實現就在xhr中
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.open('get', 'http://www.baidu.com');
......
xhr.send(null);
實現跨瀏覽器的CORS
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;
}
var request = createCORS('get', 'http://www.baidu.com');
if(request){
request.onload = function(){
......
};
request.send();
}
資料來源:
微信訂閱號(前端趣聞,歡迎關注)