DIV CSS 佈局教程網

前端跨來源請求問題的解法總整理
編輯:關於JavaScript     

跨來源(cross-origin)一直是前端開發的必經課題。要選對解法,得先搞懂瀏覽器的同源政策到底在限制什麼。

一、同源政策的判定規則

所謂「同源」,指的是協定、網域與連接埠三者完全相同。

比較的兩組網址說明是否允許通訊
https://www.a.com/a.js 與 https://www.a.com/b.js同協定同網域同埠允許
https://www.a.com/lab/a.js 與 https://www.a.com/script/b.js同網域不同目錄允許
https://www.a.com:8000/a.js 與 https://www.a.com/b.js同網域不同連接埠不允許
https://www.a.com/a.js 與 https://www.a.com/b.js同網域不同協定不允許
https://www.a.com/a.js 與 https://70.32.92.74/b.js網域與其對應 IP不允許
https://www.a.com/a.js 與 https://script.a.com/b.js主網域相同、子網域不同不允許
https://www.cnblogs.com/a.js 與 https://www.a.com/b.js完全不同的網域不允許

有兩點特別容易誤解:

第一,若是協定或連接埠造成的跨來源問題,單靠前端是無能為力的。
第二,瀏覽器判定來源時只看網址的「開頭部分」(protocol + host),不會去解析背後的 IP。也就是說,即使兩個網域指向同一台伺服器,仍然算跨來源。

二、常見解法

1. document.domain + iframe(僅限主網域相同)

a.html 端:

document.domain = 'a.com';
var ifr = document.createElement('iframe');
ifr.src = 'https://www.script.a.com/b.html';
ifr.style.display = 'none';
document.body.appendChild(ifr);
ifr.onload = function () {
  var doc = ifr.contentDocument || ifr.contentWindow.document;
  // 在此操作 doc,也就是 b.html
  ifr.onload = null;
};

b.html 端只要同樣設定一次即可:

document.domain = 'a.com';

2. 動態建立 script 標籤

script 標籤不受同源政策限制,這也是 JSONP 的基礎。

function loadScript(url, func) {
  var head = document.head || document.getElementsByTagName('head')[0];
  var script = document.createElement('script');
  script.src = url;
  script.onload = script.onreadystatechange = function () {
    if (!this.readyState || this.readyState == 'loaded' || this.readyState == 'complete') {
      func();
      script.onload = script.onreadystatechange = null;
    }
  };
  head.insertBefore(script, 0);
}

window.baidu = {
  sug: function (data) {
    console.log(data);
  }
}
loadScript('https://suggestion.baidu.com/su?wd=w', function () {
  console.log('loaded');
});

請求回來的內容可以在 Chrome 開發工具的 Sources 面板中看到。

3. location.hash + iframe

原理是透過 hash 變化傳值。假設 a.com 下的 cs1.html 要與 cnblogs.com 下的 cs2.html 溝通:

・cs1.html 建立隱藏 iframe,src 指向 cs2.html
・cs2.html 載入後,透過修改 cs1.html 的 hash 來傳遞資料
・cs1.html 用定時器輪詢 hash 是否變化

注意:由於兩頁不同源,IE 與 Chrome 不允許直接修改 parent.location.hash,因此需要一個位於 a.com 下的代理頁面居中轉傳。

// a.com/cs1.html
function startRequest() {
  var ifr = document.createElement('iframe');
  ifr.style.display = 'none';
  ifr.src = 'https://www.cnblogs.com/lab/cscript/cs2.html#paramdo';
  document.body.appendChild(ifr);
}

function checkHash() {
  try {
    var data = location.hash ? location.hash.substring(1) : '';
    console.log('Now the data is ' + data);
  } catch (e) { }
}
setInterval(checkHash, 2000);
// cnblogs.com/cs2.html
switch (location.hash) {
  case '#paramdo':
    callBack();
    break;
  case '#paramset':
    // do something...
    break;
}

function callBack() {
  try {
    parent.location.hash = 'somedata';
  } catch (e) {
    // IE、Chrome 的安全機制無法修改 parent.location.hash,
    // 因此改用一個位於 cnblogs 網域下的代理 iframe
    var ifrproxy = document.createElement('iframe');
    ifrproxy.style.display = 'none';
    ifrproxy.src = 'https://a.com/test/cscript/cs3.html#somedata';
    document.body.appendChild(ifrproxy);
  }
}
// a.com/cs3.html
// parent.parent 與自身同網域,因此可以改寫其 hash
parent.parent.location.hash = self.location.hash.substring(1);

4. window.name + iframe

window.name 的特性很適合傳值:它在不同頁面(甚至不同網域)載入後依然存在,而且可容納相當大的資料量(約 2MB)。

<head>
<script>
function proxy(url, func) {
  var isFirst = true,
      ifr = document.createElement('iframe'),
      loadFunc = function () {
        if (isFirst) {
          ifr.contentWindow.location = 'https://a.com/cs1.html'; // 導向同源的代理頁
          isFirst = false;
        } else {
          func(ifr.contentWindow.name);
          ifr.contentWindow.close();
          document.body.removeChild(ifr);
          ifr.src = '';
          ifr = null;
        }
      };
  ifr.src = url;
  ifr.style.display = 'none';
  if (ifr.attachEvent) ifr.attachEvent('onload', loadFunc);
  else ifr.onload = loadFunc;
  document.body.appendChild(ifr);
}
</script>
</head>
<body>
<script>
proxy('https://www.baidu.com/', function (data) {
  console.log(data);
});
</script>
</body>

被跨網域載入的頁面只要寫入 name 即可:

<script>
window.name = '要傳送的內容';
</script>

5. postMessage(HTML5)

<iframe id="ifr" src="b.com/index.html"></iframe>
<script type="text/javascript">
window.onload = function () {
  var ifr = document.getElementById('ifr');
  var targetOrigin = 'https://b.com'; // 若寫成 'https://c.com' 則不會送出訊息
  ifr.contentWindow.postMessage('I was there!', targetOrigin);
};
</script>
<script type="text/javascript">
window.addEventListener('message', function (event) {
  // 務必透過 origin 屬性驗證訊息來源
  if (event.origin == 'https://a.com') {
    alert(event.data);   // "I was there!"
    alert(event.source); // 對 a.com 中 window 物件的參照,
                         // 但受同源政策限制,此處不可存取其內容
  }
}, false);
</script>

6. CORS

CORS 的核心思路是透過自訂的 HTTP 標頭,讓瀏覽器與伺服器協商出「這個請求該不該成功」。IE 的實作是 XDomainRequest,其他瀏覽器則是 XMLHttpRequest 加上 withCredentials。

var xdr = new XDomainRequest();
xdr.onload = function () {
  console.log(xdr.responseText);
}
xdr.open('get', 'https://www.baidu.com');
xdr.send(null);
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
  if (xhr.readyState == 4) {
    if (xhr.status >= 200 && xhr.status < 300) {
      console.log(xhr.responseText);
    }
  }
}
xhr.open('get', 'https://www.baidu.com');
xhr.send(null);

封裝成跨瀏覽器版本:

function createCORS(method, url) {
  var xhr = new XMLHttpRequest();
  if ('withCredentials' in xhr) {
    xhr.open(method, url, true);
  } else if (typeof XDomainRequest != 'undefined') {
    xhr = new XDomainRequest();
    xhr.open(method, url);
  } else {
    xhr = null;
  }
  return xhr;
}

var request = createCORS('get', 'https://www.baidu.com');
if (request) {
  request.onload = function () {
    // 處理回應
  };
  request.send();
}

7. JSONP

JSONP 由兩部分組成:回呼函式與資料。回呼函式是回應抵達時要在目前頁面被呼叫的函式,資料則是傳入該函式的 JSON 物件。

function handleResponse(response) {
  console.log('The responsed data is: ' + response.data);
}
var script = document.createElement('script');
script.src = 'https://www.baidu.com/json/?callback=handleResponse';
document.body.insertBefore(script, document.body.firstChild);

// 原理:
// 1、透過 script 標籤發出請求
// 2、後端依 callback 參數產生 handleResponse({"data": "zhe"}) 這樣的程式碼
// 3、回傳的內容被當成 JavaScript 執行,於是回呼函式被呼叫
// 4、跨網域通訊完成

JSONP 簡單但有兩個明顯缺點:一是存在安全性隱患(回傳的程式碼會直接執行),二是難以可靠判斷請求是否失敗(script 載入失敗不會拋出可供捕捉的錯誤)。

8. WebSocket

WebSocket 是一種瀏覽器 API,目標是在單一持續連線上提供全雙工、雙向通訊,同源政策並不適用於它。

運作流程是:JavaScript 建立 WebSocket 後會先發出一個 HTTP 請求以發起連線,伺服器回應後,連線透過 HTTP Upgrade 機制從 HTTP 協定切換為 WebSocket 協定。因此它只能運作在支援 WebSocket 協定的伺服器上。

var socket = new WebSocket('ws://www.baidu.com'); // http -> ws;https -> wss
socket.send('hello WebSocket');
socket.onmessage = function (event) {
  var data = event.data;
}

選型建議

如果是全新的專案,優先考慮後端加上 CORS 標頭,這是最標準也最容易維護的方式;需要跨網域傳輸資料又無法改後端時,才回頭考慮 JSONP 或 postMessage。而 document.domain、location.hash、window.name 這幾種 iframe 變形手法,如今多數場景都能被 CORS 取代,主要還存在於需要相容舊系統的維護情境中。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved