什么是跨域
跨域是指一个域下的文档或脚本试图去请求另一个域下的资源,这里跨域是广义的。
广义的跨域:
1)资源跳转:A链接、重定向、表单提交
2)资源嵌入:、
服务端返回如下(返回时即执行全局函数):
handleCallback({"status": true, "user": "admin"})
2、jquery ajax
$.ajax({
url: 'http://www.tunan666.com:8080/login',
type: 'get',
dataType: 'jsonp', // 请求方式为jsonp
jsonpCallback: "handleCallback", // 自定义回调函数名
data: {}
});
3、vue.js
this.$http.jsonp('http://www.tunan666.com:8080/login', {
params: {},
jsonp: 'handleCallback'
}).then((res) => {
console.log(res);
})
4、后端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虽然很简单,但是有如下缺点:
1)安全问题:请求代码中可能存在安全隐患
2)要确定jsonp请求是否失败并不容易
3)只能实现get一种请求
二、iframe跨域
1、document.domain + iframe 跨域
此方案仅限主域相同,子域不同的跨域应用场景。
实现原理:两个页面都通过js强制设置document.domain为基础主域,就实现了同域。
1)父窗口:(
http://www.tunan666.com/a.html)
2)子窗口:(
http://child.tunan666.com/b.html)
2、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页面所有对象。
1)a.html:(http://www.tunan666.com/a.html)
2)b.html:(http://www.tn666.com/b.html)
3)c.html:(http://www.tunan666.com/c.html)
3、window.name + iframe 跨域
window.name属性的独特之处:name值在不同的页面(甚至不同域名)加载后依旧存在,并且可以支持非常长的 name 值(2MB)。
通过iframe的src属性由外域转向本地域,跨域数据即由iframe的window.name从外域传递到本地域。这个就巧妙地绕过了浏览器的跨域访问限制,但同时它又是安全操作。
1)a.html:(http://www.tunan666.com/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.tunan666.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.tn666.com/b.html', function(data){
alert(data);
});
2)proxy.html:(http://www.tunan666.com/proxy….
中间代理页,与a.html同域,内容为空即可。
3)b.html:(http://www.tn666.com/b.html)
三、postMessage跨域
postMessage是HTML5 XMLHttpRequest Level 2中的API,且是为数不多可以跨域操作的window属性之一,它可用于解决以下方面的问题:
1)页面和其打开的新窗口的数据传递
2)多窗口之间消息传递
3)页面与嵌套的iframe消息传递
4)上面三个场景的跨域数据传递
用法:postMessage(data,origin)方法接受两个参数
data:html5规范支持任意基本类型或可复制的对象,但部分浏览器只支持字符串,所以传参时最好用JSON.stringify()序列化。
origin:协议+主机+端口号,也可以设置为"*",表示可以传递给任意窗口,如果要指定和当前窗口同源的话设置为"/"。
1、a.html:(
http://www.tunan666.com/a.html)
2、b.html:(
http://www.tn666.com/b.html)
下一篇文章介绍剩下的几种方法:
4、跨域资源共享(CORS)
5、nginx代理跨域
6、nodejs中间件代理跨域
7、WebSocket协议跨域
敬请期待~