HTML - 跨域資源共享 (CORS)



跨域資源共享 (CORS) 是一種機制,允許在 web 瀏覽器中載入來自另一個域的受限資源。

例如,假設我們點選 HTML5 演示部分中的 HTML5 影片播放器。首先,它會請求攝像頭許可權,如果使用者允許該許可權,則只會開啟攝像頭,否則不會。

發起 CORS 請求

現代瀏覽器如 Chrome、Firefox、Opera 和 Safari 都使用 XMLHttprequest2 物件,而 Internet Explorer 使用類似的 XDomainRequest 物件。

function createCORSRequest(method, url) {
   var xhr = new XMLHttpRequest();
   
   if ("withCredentials" in xhr) {
      // Check if the XMLHttpRequest object has a "withCredentials" property.
      // "withCredentials" only exists on XMLHTTPRequest2 objects.
      xhr.open(method, url, true);
   } else if (typeof XDomainRequest != "undefined") {
      // Otherwise, check if XDomainRequest.
      // XDomainRequest only exists in IE, and is IE's way of making CORS requests.
      xhr = new XDomainRequest();
      xhr.open(method, url);
   } 
   else {
      // Otherwise, CORS is not supported by the browser.
      xhr = null;
   }
   return xhr;
}
var xhr = createCORSRequest('GET', url);
if (!xhr) {
   throw new Error('CORS not supported');
}

CORS 中的事件處理程式

序號 事件處理程式和說明
1

onloadstart

開始請求

2

onprogress

載入資料併發送資料

3

onabort

中止請求

4

onerror

請求失敗

5

onload

請求成功載入

6

ontimeout

請求完成前超時

7

onloadend

請求完成(成功或失敗)

onload 或 onerror 事件示例

xhr.onload = function() {
   var responseText = xhr.responseText;
   // process the response.
   console.log(responseText);
};
xhr.onerror = function() {
   console.log('There was an error!');
};

帶處理程式的 CORS 示例

下面的示例將展示 makeCorsRequest() 和 onload 處理程式的示例

// Create the XHR object.
function createCORSRequest(method, url) {
   var xhr = new XMLHttpRequest();
   if ("withCredentials" in xhr) {
      
      // XHR for Chrome/Firefox/Opera/Safari.
      xhr.open(method, url, true);
   } else if (typeof XDomainRequest != "undefined") {
      
      // XDomainRequest for IE.
      xhr = new XDomainRequest();
      xhr.open(method, url);
   } else {
      
      // CORS not supported.
      xhr = null;
   }
   return xhr;
}
// Helper method to parse the title tag from the response.
function getTitle(text) {
   return text.match('<title>(.*)?</title>')[1];
}

// Make the actual CORS request.
function makeCorsRequest() {
   // All HTML5 Rocks properties support CORS.
   var url = 'https://tutorialspoint.tw';
   var xhr = createCORSRequest('GET', url);
   if (!xhr) {
      alert('CORS not supported');
      return;
   }
   
   // Response handlers.
   xhr.onload = function() {
      var text = xhr.responseText;
      var title = getTitle(text);
      alert('Response from CORS request to ' + url + ': ' + title);
   };
   xhr.onerror = function() {
      alert('Woops, there was an error making the request.');
   };
   xhr.send();
}
廣告