同源策略与跨域处理

同源策略
> 原理: 协议、域名、端口都相同
> 目的: 保证用户信息安全,防止恶意网站窃取信息
> 限制: 非同源不能访问
> - cookie、localStorage、webSql、indexDB,
> - DOM无法获取
> - Ajax请求不能发送
> 没有限制: 内部的表单没限制

同源例子

[http://www.example.com/dir/page.html] 默认80端口
http://www.example.com/dir2/index.html 同源
http://example.com/dir2/index.html 不同源(二级域名与一级域名不属于同源,域名不同)
http://v2.example.com/dir2/index.html 不同源(域名不同)
http://www.example.com:8081/dir/other.html 不同源(端口不同)
https://www.example.com/dir/page.html 不同源(协议不同)

如何设置同源策略?

 

【前端方式】- 很少使用
----------- test.xxx.com/a.html ----------------
<script>
document.domain = "test2.xxx.com";//设置同源策略
document.cookie = "test1=hello";
</script>
----------- test2.xxx.com/b.html ----------------
<script>
console.log(document.cookie)
</script>
【后端方式】- 常用
Set-Cookie: key=value;domain=test2.xxx.com;path=/

 

跨域实现的几种方式
> jsonp: 利用script标签跨域请求,用callback实现

<script src="http://xxx.com/index.php?callback=test"></script>
<script>
   function test(data){console.log(data);}
</script>
//jquery
$.ajax({
   type: 'jsonp',
   success: function(data){
      //jquery自动隐式创建了一个test方法
   }
})

> CROS
> 反向代理
> websocket
> postMessage
> img: 是文件协议(不在同源策略中,因此可以访问)

//测试一下手机网速,根据网速,可以给用户出一些网速较慢的解决方案:直接跳转到简版 s.gif = 1kb
var s = new Image();
var start = Date.now();
s.src = "http://www.xxx.com/s.gif";
s.onload = function(){
   var end = Data.now();
   var t = end - start;
   v = 1kb / t;// 算出 kb/s
   var level = 10 - Math.floor(v / 100);//根据网速进行分级
   //根据分级来处理你想干的事情
}

把代码压缩成图片

> link: css可以跨域
> iframe:(不在同源策略中,因此可以访问)
> script标签(不在同源策略中,因此可以访问)

posted on 2017-11-10 16:19  爱疯的小疯子  阅读(213)  评论(0编辑  收藏  举报

导航