同源策略与跨域处理

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

同源例子css

[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 不一样源(协议不一样)

如何设置同源策略?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: 是文件协议(不在同源策略中,所以能够访问)jquery

//测试一下手机网速,根据网速,能够给用户出一些网速较慢的解决方案:直接跳转到简版 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);//根据网速进行分级
   //根据分级来处理你想干的事情
}

把代码压缩成图片web

> link: css能够跨域
> iframe:(不在同源策略中,所以能够访问)
> script标签(不在同源策略中,所以能够访问)ajax

相关文章
相关标签/搜索