什么叫同源?

  • 协议相同
  • 域名相同
  • 端口相同(浏览器没有遵守这条规定,因此端口不同,浏览器也认为其同源)*

举例来说,http://www.example.com/dir/page.html这个网址,协议是http://,域名是www.example.com,端口是80(默认端口可以省略),它的同源情况如下。

  • http://www.example.com/dir2/other.html:同源
  • http://example.com/dir/other.html:不同源(域名不同)
  • http://v2.www.example.com/dir/other.html:不同源(域名不同)
  • http://www.example.com:81/dir/other.html:不同源(端口不同)
  • https://www.example.com/dir/page.html:不同源(协议不同)

目的

用于保护用户隐私,例如用户登陆到A网站,记录了用户的storage和cookie,如果用户又登陆了B网站,B网站可以随时查看其A网站的Cookie,有隐私安全的风险

reference