什么是跨域?
跨域是指一个域下的文档或脚本试图去请求另一个域下的资源,这里跨域是广义的。
广义的跨域:
- 资源跳转:
A
链接、重定向、表单提交。 - 资源嵌入:
<link>、<script>、<img>、<frame>
等dom
标签,还有样式中background:url()
、@font-face()
等文件外链。 - 脚本请求:
js
发起的ajax
请求、dom
和js
对象的跨域操作等。
其实我们通常所说的跨域是狭义的,是由浏览器同源策略限制的一类请求场景。
什么是同源策略?
同源策略/SOP
(Same origin policy
)是一种约定,由Netscape
公司1995年引入浏览器,它是浏览器最核心也最基本的安全功能,如果缺少了同源策略,浏览器很容易受到XSS
、CSFR
等攻击。
所谓同源是指"协议+域名+端口"三者相同,即便两个不同的域名指向同一个ip
地址,也非同源。
同源策略限制以下几种行为:
Cookie
、LocalStorage
和IndexDB
无法读取。DOM
和Js
对象无法获得。AJAX
请求不能发送。
常见跨域场景
URL 说明 是否允许通信
http://www.domain.com/a.js
http://www.domain.com/b.js 同一域名,不同文件或路径 允许
http://www.domain.com/lab/c.js
http://www.domain.com:8000/a.js
http://www.domain.com/b.js 同一域名,不同端口 不允许
http://www.domain.com/a.js
https://www.domain.com/b.js 同一域名,不同协议 不允许
http://www.domain.com/a.js
http://192.168.4.12/b.js 域名和域名对应相同ip 不允许
http://www.domain.com/a.js
http://x.domain.com/b.js 主域相同,子域不同 不允许
http://domain.com/c.js
http://www.domain1.com/a.js
http://www.domain2.com/b.js 不同域名 不允许
跨域解决方案
- 通过
jsonp
跨域 document.domain + iframe
跨域location.hash + iframe
window.name + iframe
跨域postMessage
跨域- 跨域资源共享(
CORS
) nginx
代理跨域nodejs
中间件代理跨域WebSocket
协议跨域
一、 通过jsonp
跨域
通常为了减轻web
服务器的负载,我们把js、css,img
等静态资源分离到另一台独立域名的服务器上。
在html
页面中再通过相应的标签从不同域名下加载静态资源,而被浏览器允许,基于此原理,我们可以通过动态创建script
,再请求一个带参网址实现跨域通信。
原生实现:
<script>
var script = document.createElement('script');
script.type = 'text/javascript';
// 传参一个回调函数名给后端,方便后端返回时执行这个在前端定义的回调函数
script.src = 'http://www.domain2.com:8080/login?user=admin&callback=handleCallback';
document.head.appendChild(script);
// 回调执行函数
function handleCallback(res) {
alert(JSON.stringify(res));
}
</script>
服务端返回如下(返回时即执行全局函数):
handleCallback({"status": true, "user": "admin"})
jquery ajax
:
$.ajax({
url: 'http://www.domain2.com:8080/login',
type: 'get',
dataType: 'jsonp', // 请求方式为jsonp
jsonpCallback: "handleCallback", // 自定义回调函数名
data: {}
});
vue.js
this.$http.jsonp('http://www.domain2.com:8080/login', {
params: {},
jsonp: 'handleCallback'
}).then((res) => {
console.log(res);
})
后端node.js
代码示例
var querystring = require('querystring');
var http = require('http');
var server = http.createServer();
server.on('request', function(req, res) {
var params = qs.parse(req.url.split('?')[1]);
var fn = params.callback;
// jsonp返回设置
res.writeHead(200, { 'Content-Type': 'text/javascript' });
res.write(fn + '(' + JSON.stringify(params) + ')');
res.end();
});
server.listen('8080');
console.log('Server is running at port 8080...');
jsonp
缺点:只能实现get
一种请求。
二、 document.domain + iframe
跨域
此方案仅限主域相同,子域不同的跨域应用场景。
实现原理:两个页面都通过js
强制设置document.domain
为基础主域,就实现了同域。
父窗口
<iframe id="iframe" src="http://child.domain.com/b.html"></iframe>
<script>
document.domain = 'domain.com';
var user = 'admin';
</script>
子窗口
<script>
document.domain = 'domain.com';
// 获取父窗口中变量
alert('get js data from parent ---> ' + window.parent.user);
</script>
三、 location.hash + iframe
跨域
实现原理: a
欲与b
跨域相互通信,通过中间页c
来实现。 三个页面,不同域之间利用iframe
的location.hash
传值,相同域之间直接js
访问来通信。
具体实现:A域:a.html
-> B域:b.html
-> A域:c.html
,a
与b
不同域只能通过hash
值单向通信,b
与c
也不同域也只能单向通信,但c
与a
同域,所以c
可通过parent.parent
访问a
页面所有对象。
a.html
<iframe id="iframe" src="http://www.domain2.com/b.html" style="display:none;"></iframe>
<script>
var iframe = document.getElementById('iframe');
// 向b.html传hash值
setTimeout(function() {
iframe.src = iframe.src + '#user=admin';
}, 1000);
// 开放给同域c.html的回调方法
function onCallback(res) {
alert('data from c.html ---> ' + res);
}
</script>
b.html
<iframe id="iframe" src="http://www.domain1.com/c.html" style="display:none;"></iframe>
<script>
var iframe = document.getElementById('iframe');
// 监听a.html传来的hash值,再传给c.html
window.onhashchange = function () {
iframe.src = iframe.src + location.hash;
};
</script>
c.html
<script>
// 监听b.html传来的hash值
window.onhashchange = function () {
// 再通过操作同域a.html的js回调,将结果传回
window.parent.parent.onCallback('hello: ' + location.hash.replace('#user=', ''));
};
</script>
四、 window.name + iframe
跨域
window.name
属性的独特之处:name
值在不同的页面(甚至不同域名)加载后依旧存在,并且可以支持非常长的 name
值(2MB
)。
a.html
var proxy = function(url, callback) {
var state = 0;
var iframe = document.createElement('iframe');
// 加载跨域页面
iframe.src = url;
// onload事件会触发2次,第1次加载跨域页,并留存数据于window.name
iframe.onload = function() {
if (state === 1) {
// 第2次onload(同域proxy页)成功后,读取同域window.name中数据
callback(iframe.contentWindow.name);
destoryFrame();
} else if (state === 0) {
// 第1次onload(跨域页)成功后,切换到同域代理页面
iframe.contentWindow.location = 'http://www.domain1.com/proxy.html';
state = 1;
}
};
document.body.appendChild(iframe);
// 获取数据以后销毁这个iframe,释放内存;这也保证了安全(不被其他域frame js访问)
function destoryFrame() {
iframe.contentWindow.document.write('');
iframe.contentWindow.close();
document.body.removeChild(iframe);
}
};
// 请求跨域b页面数据
proxy('http://www.domain2.com/b.html', function(data){
alert(data);
});
proxy.html
中间代理页,与a.html
同域,内容为空即可。
b.html
<script>
window.name = 'This is domain2 data!';
</script>
总结:通过iframe
的src
属性由外域转向本地域,跨域数据即由iframe
的window.name
从外域传递到本地域。这个就巧妙地绕过了浏览器的跨域访问限制,但同时它又是安全操作。
五、 postMessage
跨域
postMessage
是HTML5 XMLHttpRequest Level 2
中的API
,且是为数不多可以跨域操作的window
属性之一,它可用于解决以下方面的问题:
- 页面和其打开的新窗口的数据传递
- 多窗口之间消息传递
- 页面与嵌套的
iframe
消息传递 - 上面三个场景的跨域数据传递
六、跨域资源共享(CORS
)
普通跨域请求:只服务端设置Access-Control-Allow-Origin
即可,前端无须设置,若要带cookie
请求:前后端都需要设置。
需注意的是:由于同源策略的限制,所读取的cookie
为跨域请求接口所在域的cookie
,而非当前页。
Q.E.D.