同源策略和跨域方法

同源策略

同源策略阻止從一個域上加載的腳本獲取或操做另外一個域上的文檔屬性。也就是說,受到的請求的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

相關文章
相關標籤/搜索