天天看點

【9大跨域解決方案】document.domain解決跨域的原理

document.domain筆記

一級域名與二級域名

直接看例子就能明白:
  • 一級域名:www.baidu.com
  • 二級域名:music.baidu.com
顯然,這是跨域的

本地設定不同域名

可以通過配置host檔案來設定不同的域名
  • 一般host檔案的目錄為:C:\Windows\System32\drivers\etc
127.0.0.1       www.yuhua.com
    127.0.0.1       a.yuhua.com
    127.0.0.1       b.yuhua.com
           
這樣的配置的意思就是,當你去通路www.yuhua.com 或 a.yuhua.com 或 b.yuhua.com的時候,會去通路對應位址前面的ip,這裡,這三個域名都是會去通路127.0.0.1

如何通過document.domain實作跨域

document.domain這個方法使用極其簡單,但是也有較大的限制,主要用于主域相同的域之間的資料通信。

下面簡單舉例說明:

  • 前提準備:
  • http://a.yuhua.com:3000/a.html起a.html
  • http://b.yuhua.com:3000/b.html起b.html
顯然,兩者是跨域的。
  • 需求:在a上擷取b的資料
  • 思路:通過document.domain為"yuhua.com"的方式擷取
  • 具體實作:
//a.html
 <iframe src="http://b.yuhua.com:4000/b.html" "load()" id="frame"></iframe>
 <script type="text/javascript">
   document.domain = 'yuhua.com';
   function load(){
    console.log(frame.contentWindow.name);
   }
 </script>

 //b.html
 <script type="text/javascript">
  document.domain = 'yuhua.com';
  var name = 'yuhua';
 </script>
           
  • 現象:加載a.html,會列印"yuhua"
  • 原因分析:當主域之間互相通信的時候,隻要将兩者的document.domain指派為目前的主域位址,即可實作跨域通信。

實作跨域的9種方法(點選可跳轉詳情頁面)

  • jsonp
  • cors
  • postMessage
  • document.domain
  • window.name
  • location.hash
  • http-proxy 後續會有詳細文章闡述
  • nginx 後續會有詳細版塊闡述
  • websocket