同源的定义
相同的协议、端口和域名:
比如针对http://store.company.com/dir/page.html:
- http://store.company.com/dir2/other.html 同源
- http://store.company.com/dir/inner/another.html 同源
- https://store.company.com/secure.html 不同源,协议不同
- http://store.company.com:81/dir/etc.html 不同源,端口不同
- http://news.company.com/dir/other.html 不同源,域名不同
更改源
可以通过document.domain设置,但只能设置为当前域或者当前域的超级域。
譬如将http://store.company.com/dir/page.html
和http://news.company.com/dir/other.html
的域名都设置:
document.domain = "company.com";
那么现在这两个网址就是同源的了。
但是不能将http://store.company.com/dir/other.html
的域名设置为 news.company.com
跨域访问
以下几种情况是默认允许跨域的:
- script标签嵌入的脚本
- link嵌入css
- img嵌入图片
<video>
和<audio>
嵌入多媒体资源。- @font-face引入的字体。一些浏览器允许跨域字体( cross-origin fonts),一些需要同源字体(same-origin fonts)。
<frame>
和<iframe>
载入的任何资源
跨域存储
- localStorage都是以源作为分割的,每个源拥有自己的存储空间,不能跨域存储。
cookie:一个页面可以为本域和任何父域设置cookie。
浏览器也允许给定的域以及其任何子域名(sub-domains)来访问cookie。
设置cookie时,可以使用domain、path、secure等属性来标记其访问性。window.name可以用来临时存储数据,可以跨域访问。