同源
概念:协议,域名,端口 相同。
目的:保证用户信息的安全,防止恶意的网站窃取数据。
限制的行为:html
- Cookie、LocalStorage 和 IndexDB 没法读取。
- DOM 没法得到。
- AJAX 请求不能发送。
跨域
- 资源跳转: A连接、重定向、表单提交
- 资源嵌入: <link>、<script>、<img>、<frame>等dom标签,还有样式中background:url()、@font-face()等文件外链
- 脚本请求: js发起的ajax请求、dom和js对象的跨域操做等
解决方案
-
场景:前端
- 两个网页一级域名相同,二级域名不一样,须要共享 Cookie
- iframe窗口和window.open的窗口,须要与父窗口通讯。
-
方案:ajax
- 浏览器设置一级域名。
document.domain = 'example.com';
- 服务器设置一级域名。
Set-Cookie: key=value; domain=.example.com; path=/
- MessageChannel
-
场景:跨域
-
方案:浏览器
- 父子窗口(互相)写location.hash,(互相)监听hashchange
- 子窗口写window.name后跳回同域,父窗口读window.name
- 浏览器跨文档通讯 window.postMessage
-
场景:安全
-
方案:服务器
- 架设服务器代理
- JSONP
- WebSocket
- CORS
参考资料
浏览器同源政策及其规避方法 - 阮一峰
前端常见跨域解决方案(全)
跨域几种方式dom