# 前端常见跨域解决方案
# 跨域的定义
由于同源策略的限制,如果 协议、域名、端口,即会形成跨域。
# 跨域解决方案
# 一、通过jsonp跨域
由于script标签并没有跨域的限制,所以可以通过动态生成script标签访问后台请求,服务端封装数据返回执行代码。
# 二、document.domain + iframe跨域
此方案仅限主域相同,子域不同的跨域场景。
实现原理:两个页面通过js强制设置domain为基础主域,实现跨域
- 父窗口(http://www.domain.com/a.html)
<iframe id="iframe" src="http://child.domain.com/b.html"></iframe>
<script>
document.domain = domain.com
var user = 'admin'
</script>
1
2
3
4
5
2
3
4
5
- 子窗口(http://child.domain.com/b.html)
<script>
document.domain = 'domain.com'
// 获取父窗口的变量
alert('get js data from parent:'+ window.parent.user)
</script>
1
2
3
4
5
2
3
4
5
# 三、location.hash + iframe跨域
实现原理:a和b跨域通信,通过中间页c来实现。三个页面,不同域之间利用iframe的location.hash传值,相同于之间直接js访问来通信
- a.html(http://www.domain1.com)
<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>
1
2
3
4
5
6
7
8
9
10
11
12
2
3
4
5
6
7
8
9
10
11
12
- b.html(http://www.domain2.com)
<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>
1
2
3
4
5
6
7
8
2
3
4
5
6
7
8
- c.html(http://www.domain1.com/c.html)
<script>
// 监听b.html传来的hash值
window.onhashchange = function(){
// 再通过操作同域a.html的js回调,将结果传回
window.parent.parent.onCallback('hello:'+location.hash.replace('#user=', ''))
}
</script>
1
2
3
4
5
6
7
2
3
4
5
6
7
# 四、window.name + iframe跨域
window.name属性的独特之处:name值在不同的页面(甚至不同的域名)加载后依旧存在,并且支持非常长的name值(2M)
- a.html(http://www.domain1.com)
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);
});
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
35
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
35
- proxy.html:(http://www.domain1.com)
中间代理页,与a.html同域,内容为空即可。 3. b.html(http://www.domain2.com)
<script>
window.name = 'This is domain2 data!';
</script>
1
2
3
2
3
# 五、postMessage跨域
postMessage是HTML5 XMLHttpRequest Level 2中的API,且是为数不多可以跨域操作的window属性之一,他可用于解决以下的问题:
a. 页面和其打开的新窗口的数据传递
b. 多窗口之间消息传递
c. 页面与嵌套的iframe消息传递
d. 上面三个场景的跨域数据传递
用法: postMessage(data, orgin)方法接受两个参数
data: H5规范支持任意基本类型和可复制的对象,但部分浏览器仅支持字符串,所以传参最好用JSON.stringify序列化
origin:协议+主机+端口号,也可以设置为'*',指定同源设置为'/'
- a.html:(http://www.domain1.com/a.html)
<iframe id="iframe" src="http://www.domain2.com/b.html" style="display:none;"></iframe>
<script>
var iframe = document.getElementById('iframe');
iframe.onload = function() {
var data = {
name: 'aym'
};
// 向domain2传送跨域数据
iframe.contentWindow.postMessage(JSON.stringify(data), 'http://www.domain2.com');
};
// 接受domain2返回数据
window.addEventListener('message', function(e) {
alert('data from domain2 ---> ' + e.data);
}, false);
</script>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
- b.html:(http://www.domain2.com/b.html)
<script>
// 接收domain1的数据
window.addEventListener('message', function(e) {
alert('data from domain1 ---> ' + e.data);
var data = JSON.parse(e.data);
if (data) {
data.number = 16;
// 处理后再发回domain1
window.parent.postMessage(JSON.stringify(data), 'http://www.domain1.com');
}
}, false);
</script>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
2
3
4
5
6
7
8
9
10
11
12
13
14
# 六、跨域资源共享(cors)
服务器端设置
- Java
// 允许跨域访问的域名:若有端口需写全(协议+域名+端口),若没有端口末尾不用加'/'
response.setHeader("Access-Control-Allow-Origin", "http://www.domain1.com");
// 允许前端带认证cookie:启用此项后,上面的域名不能为'*',必须指定具体的域名,否则浏览器会提示
response.setHeader("Access-Control-Allow-Credentials", "true");
1
2
3
4
5
2
3
4
5
- Nodejs
var http = require('http');
var server = http.createServer();
var qs = require('querystring');
server.on('request', function(req, res) {
var postData = '';
// 数据块接收中
req.addListener('data', function(chunk) {
postData += chunk;
});
// 数据接收完毕
req.addListener('end', function() {
postData = qs.parse(postData);
// 跨域后台设置
res.writeHead(200, {
'Access-Control-Allow-Credentials': 'true', // 后端允许发送Cookie
'Access-Control-Allow-Origin': 'http://www.domain1.com', // 允许访问的域(协议+域名+端口)
/*
* 此处设置的cookie还是domain2的而非domain1,因为后端也不能跨域写cookie(nginx反向代理可以实现),
* 但只要domain2中写入一次cookie认证,后面的跨域接口都能从domain2中获取cookie,从而实现所有的接口都能跨域访问
*/
'Set-Cookie': 'l=a123456;Path=/;Domain=www.domain2.com;HttpOnly' // HttpOnly的作用是让js无法读取cookie
});
res.write(JSON.stringify(postData));
res.end();
});
});
server.listen('8080');
console.log('Server is running at port 8080...');
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
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