同源策略和跨域方法

同源策略

同源策略阻止从一个域上加载的脚本获取或操做另外一个域上的文档属性。也就是说,受到的请求的URL的域必须与当前Web页面的域相同。存在如下任一状况,即发生跨域:html

  • 网络协议不一样,如http协议访问https协议;
  • 端口不一样,如80端口访问8080端口;
  • 域名不一样,如aaa.com访问bbb.com;
  • 子域不一样,如abc.qq.com访问123.qq.com。

 

克服的方法&跨域原理

1. 基于iframenode

对于主域名(基础域名)相同而子域名不一样的状况,也就是两个页面必须属于同一个基础域,使用赞成协议(例如http)和同一端口。能够经过这种方法来解决。能够在http://www.example.com/a.html和http://api.example.com/b.html两个文件中分别添加document.domain = ‘example.com’,而后在a.html中建立一个iframe指向b.html,即a.html是父页面,b.html是个子页面。api

www.example.com上的a.html:跨域

<html> 

<head> 

  <script> 

   document.domain = "example.com"; 

    var ifr = document.createElement('iframe');

    ifr.src = 'http://api.example.com/b.html';   

    ifr.style.display = 'none';

    document.body.appendChild(ifr);

 

ifr.onload = function(){

    var doc = ifr.contentDocument || ifr.contentWindow.document;

    // 在这里操纵b.html
    alert(doc.getElementsByTagName("h1")[0].childNodes[0].nodeValue);

};

  </script> 

</head> 

<body> 

 
 </body> 

</html> 

 

api.example.com上的b.html浏览器

<html>

 <head>

  <script>

    document.domain = "example.com";

    function a(){

    alert("c");

     }

  </script>

 </head>

 <body>

 </body>

</html>

 

注意:安全

  1. 某一页面的domain默认等于window.location.hostname。要注意区分主域名和二级多级域名。
  2. 可能出现安全问题,若是一个站点www.example.com被攻击,另外一个站点api.example.com也会引发安全漏洞。

 

2. 动态建立script标签网络

script标签能够访问任何域的资源,不受浏览器同源策略的限制,因此能够经过在页面动态建立script标签的方法来实现跨域。app

    var script = document.createElement('script');
    script.src = "http://www.example.com/js/*.js";
    document.body.appendChild(script);

 

这样就加载到了其余域的js文件,而后能够在本页面内调用加载的js文件中的函数。JSONP就是经过这个方式实现的,实现细节有些不一样。dom

 

其余跨域方法能够参考如下两篇文章:函数

http://www.cnblogs.com/rainman/archive/2011/02/20/1959325.html#m3

http://narutolby.iteye.com/blog/1464436

相关文章
相关标签/搜索