本文介紹跨域的八種方法:
JSONP
只要說(shuō)到跨域,就必須聊到 JSONP,JSONP全稱(chēng)為:JSON with Padding,可用于解決主流瀏覽器的跨域數(shù)據(jù)訪(fǎng)問(wèn)的問(wèn)題。
Web 頁(yè)面上調(diào)用 js 文件不受瀏覽器同源策略的影響,所以通過(guò) Script 便簽可以進(jìn)行跨域的請(qǐng)求:
html中script標(biāo)簽可以引入其他域下的js,不受同源策略的限制比如引入線(xiàn)上的jquery庫(kù)。利用這個(gè)特性,可實(shí)現(xiàn)跨域訪(fǎng)問(wèn)接口。需要后端支持
script標(biāo)簽:在頁(yè)面中動(dòng)態(tài)插入script,script標(biāo)簽的src屬性就是后端api接口的地址;這樣加載script標(biāo)簽?zāi)_本直接調(diào)用本地方法,而script標(biāo)簽會(huì)立即執(zhí)行腳本,示例:getNews?callback=appendHtml
后端:后端需要解析callback參數(shù)值,并將該值和返回?cái)?shù)據(jù)拼接。示例:res.send(req.query.callback + '(' + JSON.stringify(data) + ')')
后端頁(yè)面:
app.get('/getNews',function(req,res){
var news = [
'123',
'456',
'789',
'321',
'654',
'987',
'753',
'159',
'852'
]
var data = []
for(var i=0;i<3;i++){
var index = parseInt(Math.random() * news.length)
data.push(news[index])
news.splice(index,1)
}
var cb = req.query.callback
var show = cb + '(' + JSON.stringify(data) + ')'
console.log(show)
if(cb){
res.send(show)
}else{
res.send(data)
}
})
前端頁(yè)面:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<div class="container">
<ul class="news">
<li>233</li>
<li>323</li>
<li>332</li>
</ul>
<button class="change">換一組</button>
</div>
<script>
let $ = (className) => document.querySelector(className)
$('.change').addEventListener('click',function(){
var script = document.createElement('script')
script.src = 'http://localhost:8080/getNews?callback=appendHtml'
document.head.appendChild(script)
document.head.removeChild(script)
})
// appendHtml(["321","987","159"])
function appendHtml(news){
var html = ''
for(var i=0;i<news.length;i++){
html += '<li>' + news[i] + '</li>'
}
console.log(html)
$('.news').innerHTML = html
}
</script>
</body>
</html>
優(yōu)點(diǎn):
- 它不像XMLHttpRequest 對(duì)象實(shí)現(xiàn) Ajax 請(qǐng)求那樣受到同源策略的限制
- 兼容性很好,在古老的瀏覽器也能很好的運(yùn)行
- 不需要 XMLHttpRequest 或 ActiveX 的支持;并且在請(qǐng)求完畢后可以通過(guò)調(diào)用 callback 的方式回傳結(jié)果。
缺點(diǎn):
- 它支持 GET 請(qǐng)求而不支持 POST 等其它類(lèi)行的 HTTP 請(qǐng)求。
- 它只支持跨域 HTTP 請(qǐng)求這種情況,不能解決不同域的兩個(gè)頁(yè)面或 iframe 之間進(jìn)行數(shù)據(jù)通信的問(wèn)題
CORS
CORS 是一個(gè) W3C 標(biāo)準(zhǔn),全稱(chēng)是"跨域資源共享"(Cross-origin resource sharing)它允許瀏覽器向跨源服務(wù)器,發(fā)出 XMLHttpRequest 請(qǐng)求,從而克服了 ajax 只能同源使用的限制。
CORS 需要瀏覽器和服務(wù)器同時(shí)支持才可以生效,對(duì)于開(kāi)發(fā)者來(lái)說(shuō),CORS 通信與同源的 ajax 通信沒(méi)有差別,代碼完全一樣。瀏覽器一旦發(fā)現(xiàn) ajax 請(qǐng)求跨源,就會(huì)自動(dòng)添加一些附加的頭信息,有時(shí)還會(huì)多出一次附加的請(qǐng)求,但用戶(hù)不會(huì)有感覺(jué)。
因此,實(shí)現(xiàn) CORS 通信的關(guān)鍵是服務(wù)器。只要服務(wù)器實(shí)現(xiàn)了 CORS 接口,就可以跨源通信。
首先前端先創(chuàng)建一個(gè) index.html 頁(yè)面:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>CORS</title>
</head>
<body>
<script>
const xhr = new XMLHttpRequest();
xhr.open('GET', 'http://127.0.0.1:3000', true);
xhr.onreadystatechange = function() {
if(xhr.readyState === 4 && xhr.status === 200) {
alert(xhr.responseText);
}
}
xhr.send(null);
</script>
</body>
</html>
這似乎跟一次正常的異步 ajax 請(qǐng)求沒(méi)有什么區(qū)別,關(guān)鍵是在服務(wù)端收到請(qǐng)求后的處理:
require('http').createServer((req, res) => {
res.writeHead(200, {
'Access-Control-Allow-Origin': 'http://localhost:8080'
});
res.end('這是你要的數(shù)據(jù):1111');
}).listen(3000, '127.0.0.1');
console.log('啟動(dòng)服務(wù),監(jiān)聽(tīng) 127.0.0.1:3000');
關(guān)鍵是在于設(shè)置相應(yīng)頭中的 Access-Control-Allow-Origin,該值要與請(qǐng)求頭中 Origin 一致才能生效,否則將跨域失敗
成功的關(guān)鍵在于 Access-Control-Allow-Origin 是否包含請(qǐng)求頁(yè)面的域名,如果不包含的話(huà),瀏覽器將認(rèn)為這是一次失敗的異步請(qǐng)求,將會(huì)調(diào)用 xhr.onerror 中的函數(shù)
CORS 的優(yōu)缺點(diǎn):
- 使用簡(jiǎn)單方便,更為安全
- 支持 POST 請(qǐng)求方式
- CORS 是一種新型的跨域問(wèn)題的解決方案,存在兼容問(wèn)題,僅支持 IE 10 以上
Server Proxy
服務(wù)器代理,顧名思義,當(dāng)你需要有跨域的請(qǐng)求操作時(shí)發(fā)送請(qǐng)求給后端,讓后端幫你代為請(qǐng)求,然后最后將獲取的結(jié)果發(fā)送給你。
假設(shè)有這樣的一個(gè)場(chǎng)景,你的頁(yè)面需要獲取 CNode:Node.js專(zhuān)業(yè)中文社區(qū) 論壇上一些數(shù)據(jù),如通過(guò) https://cnodejs.org/api/v1/topics,當(dāng)時(shí)因?yàn)椴煌颍阅憧梢詫⒄?qǐng)求后端,讓其對(duì)該請(qǐng)求代為轉(zhuǎn)發(fā)。
const url = require('url');
const http = require('http');
const https = require('https');
const server = http.createServer((req, res) => {
const path = url.parse(req.url).path.slice(1);
if(path === 'topics') {
https.get('https://cnodejs.org/api/v1/topics', (resp) => {
let data = "";
resp.on('data', chunk => {
data += chunk;
});
resp.on('end', () => {
res.writeHead(200, {
'Content-Type': 'application/json; charset=utf-8'
});
res.end(data);
});
})
}
}).listen(3000, '127.0.0.1');
console.log('啟動(dòng)服務(wù),監(jiān)聽(tīng) 127.0.0.1:3000');
document.domain(降域)
document.domain 的作用是用來(lái)獲取/設(shè)置當(dāng)前文檔的原始域部分,例如:
// 對(duì)于文檔 www.example.xxx/good.html
document.domain="www.example.xxx"
// 對(duì)于URI http://developer.mozilla.org/en/docs/DOM
document.domain="developer.mozilla.org"
對(duì)于主域相同而子域不同的情況下,可以通過(guò)設(shè)置document.domain 的辦法來(lái)解決,具體做法是可以在http://a.jirengu.com:8080/a.html和http://b.jirengu.com:8080/b.html之中設(shè)置document.domain = 'jirengu.com'
a.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
iframe{
width: 400px;
height: 300px;
border: 1px solid #ccc;
}
</style>
</head>
<body>
<div class="ct">
<h1>使用降域?qū)崿F(xiàn)跨域</h1>
<div class="main">
<input type="text" placeholder="http://a.jirengu.com:8080/a.html">
</div>
<iframe src="http://b.jirengu.com:8080/b.html"></iframe>
</div>
<script>
// http://a.jirengu.com:8080/a.html
document.querySelector('.main input').addEventListener('click',function(){
console.log(this.value)
window.frames[0].document.querySelector('input').value = this.value
})
document.domain = 'jirengu.com'
</script>
</body>
</html>
b.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
html,body{
margin: 0;
padding: 0;
}
input{
margin: 20px;
width: 200px;
}
</style>
</head>
<body>
<input id="input" type="text" placeholder="http://b.jirengu.com:8080/b.html">
<script>
document.querySelector('#input').addEventListener('click',function(){
window.parent.document.querySelector('input').value = this.value
})
document.domain = 'jirengu.com' //降域
</script>
</body>
</html>
document.domain 的優(yōu)點(diǎn)在于解決了主語(yǔ)相同的跨域請(qǐng)求,但是其缺點(diǎn)也是很明顯的:比如一個(gè)站點(diǎn)受到攻擊后,另一個(gè)站點(diǎn)會(huì)因此引起安全漏洞;若一個(gè)頁(yè)面中引入多個(gè) iframe,想要操作所有的 iframe 則需要設(shè)置相同的 domain。
window.postMessage
postMessage 是 HTML5 新增加的一項(xiàng)功能,跨文檔消息傳輸(Cross Document Messaging),目前:Chrome 2.0+、Internet Explorer 8.0+, Firefox 3.0+, Opera 9.6+, 和 Safari 4.0+ 都支持這項(xiàng)功能,使用起來(lái)也特別簡(jiǎn)單。
首先創(chuàng)建 a.html 文件:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>a.html</title>
</head>
<body>
<iframe src="http://localhost:8081/b.html" style='display: none;'></iframe>
<script>
window.onload = function() {
let targetOrigin = 'http://localhost:8081';
window.frames[0].postMessage('我要給你發(fā)消息了!', targetOrigin);
}
window.addEventListener('message', function(e) {
console.log('a.html 接收到的消息:', e.data);
});
</script>
</body>
</html>
創(chuàng)建一個(gè) iframe,使用 iframe 的一個(gè)方法 postMessage 可以向http://localhost:8081/b.html 發(fā)送消息,然后監(jiān)聽(tīng) message,可以獲得其他文檔發(fā)來(lái)的消息。
同樣的 b.html 文件:
<script>
window.addEventListener('message', function(e) {
if(e.source != window.parent) {
return;
}
let data = e.data;
console.log('b.html 接收到的消息:', data);
parent.postMessage('我已經(jīng)接收到消息了!', e.origin);
});
</script>
location.hash
location.hash 是一個(gè)可讀可寫(xiě)的字符串,該字符串是 URL 的錨部分(從 # 號(hào)開(kāi)始的部分)。例如:
// 對(duì)于頁(yè)面 http://example.com:1234/test.htm#part2
location.hash = "#part2"
同時(shí),由于我們知道改變 hash 并不會(huì)導(dǎo)致頁(yè)面刷新,所以可以利用 hash 在不同源間傳遞數(shù)據(jù)。
假設(shè) github.io 域名下 a.html 和 shaonian.eu 域名下 b.html 存在跨域請(qǐng)求,那么利用 location.hash 的一個(gè)解決方案如下:
- a.html 頁(yè)面中創(chuàng)建一個(gè)隱藏的 iframe, src 指向 b.html,其中 src 中可以通過(guò) hash 傳入?yún)?shù)給 b.html
- b.html 頁(yè)面在處理完傳入的 hash 后通過(guò)修改 a.html 的 hash 值達(dá)到將數(shù)據(jù)傳送給 a.html 的目的
- a.html 頁(yè)面添加一個(gè)定時(shí)器,每隔一定時(shí)間判斷自身的 location.hash 是否變化,以此響應(yīng)處理
以上步驟中需要注意第二點(diǎn):如何在 iframe 頁(yè)面中修改 父親頁(yè)面的 hash 值。由于在 IE 和 Chrome 下,兩個(gè)不同域的頁(yè)面是不允許 parent.location.hash 這樣賦值的,所以對(duì)于這種情況,我們需要在父親頁(yè)面域名下添加另一個(gè)頁(yè)面來(lái)實(shí)現(xiàn)跨域請(qǐng)求,具體如下:
- 假設(shè) a.html 中 iframe 引入了 b.html, 數(shù)據(jù)需要在這兩個(gè)頁(yè)面之間傳遞,且 c.html 是一個(gè)與 a.html 同源的頁(yè)面
- a.html 通過(guò) iframe 將數(shù)據(jù)通過(guò) hash 傳給 b.html
- b.html 通過(guò) iframe 將數(shù)據(jù)通過(guò) hash 傳給 c.html
- c.html 通過(guò) parent.parent.location.hash 設(shè)置 a.html 的 hash 達(dá)到傳遞數(shù)據(jù)的目的
location.hash 方法的優(yōu)點(diǎn)在于可以解決域名完全不同的跨域請(qǐng)求,并且可以實(shí)現(xiàn)雙向通訊;而缺點(diǎn)則包括以下幾點(diǎn):
- 利用這種方法傳遞的數(shù)據(jù)量受到 url 大小的限制,傳遞數(shù)據(jù)類(lèi)型有限
- 由于數(shù)據(jù)直接暴露在 url 中則存在安全問(wèn)題
- 若瀏覽器不支持 onhashchange 事件,則需要通過(guò)輪訓(xùn)來(lái)獲知 url 的變化
- 有些瀏覽器會(huì)在 hash 變化時(shí)產(chǎn)生歷史記錄,因此可能影響用戶(hù)體驗(yàn)
window.name
window.name的值不是一個(gè)普通的全局變量,而是當(dāng)前窗口的名字,這里要注意的是每個(gè) iframe 都有包裹它的 window,而這個(gè) window 是top window 的子窗口,而它自然也有 window.name 的屬性,window.name 屬性的神奇之處在于 name 值在不同的頁(yè)面(甚至不同域名)加載后依舊存在(如果沒(méi)修改則值不會(huì)變化),并且可以支持非常長(zhǎng)的 name 值(2MB)。
舉個(gè)簡(jiǎn)單的例子:你在某個(gè)頁(yè)面的控制臺(tái)輸入:
window.name = "Hello World";window.location = "http://www.baidu.com";
頁(yè)面跳轉(zhuǎn)到了百度首頁(yè),但是 window.name 卻被保存了下來(lái),還是 Hello World,跨域解決方案似乎可以呼之欲出了:
首先創(chuàng)建 a.html 文件:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>a.html</title>
</head>
<body>
<script>
let data = '';
const ifr = document.createElement('iframe');
ifr.src = "http://localhost:8081/b.html";
ifr.style.display = 'none';
document.body.appendChild(ifr);
ifr.onload = function() {
ifr.onload = function() {
data = ifr.contentWindow.name;
console.log('收到數(shù)據(jù):', data);
}
ifr.src = "http://localhost:8080/c.html";
}
</script>
</body>
</html>
之后再創(chuàng)建 b.html 文件:
<script> window.name = "你想要的數(shù)據(jù)!";</script>
http://localhost:8080/a.html在請(qǐng)求遠(yuǎn)端服務(wù)器 http://localhost:8081/b.html的數(shù)據(jù),我們可以在該頁(yè)面下新建一個(gè) iframe,該 iframe 的 src 屬性指向服務(wù)器地址,(利用 iframe 標(biāo)簽的跨域能力),服務(wù)器文件 b.html 設(shè)置好 window.name 的值。
但是由于 a.html 頁(yè)面和該頁(yè)面 iframe 的 src 如果不同源的話(huà),則無(wú)法操作 iframe 里的任何東西,所以就取不到 iframe 的 name 值,所以我們需要在 b.html 加載完后重新?lián)Q個(gè) src 去指向一個(gè)同源的 html 文件,或者設(shè)置成 'about:blank;' 都行,這時(shí)候我只要在 a.html 相同目錄下新建一個(gè) c.html 的空頁(yè)面即可。如果不重新指向 src 的話(huà)直接獲取的 window.name 的話(huà)會(huì)報(bào)錯(cuò)。
WebSocket
WebSocket 協(xié)議不實(shí)行同源政策,只要服務(wù)器支持,就可以通過(guò)它進(jìn)行跨源通信。
參考鏈接: