如何在網路瀏覽器中使用 HTML5 來訪問另一個域中的受限資源


跨源資源共享 (CORS) 是一種機制,旨在允許網路瀏覽器中訪問另一個域中的受限資源

例如,如果你在 HTML5 示例部分中單擊 HTML5 影片播放器。它會要求訪問攝像頭許可權。如果使用者允許該許可權,則只有這樣才會開啟攝像頭,否則該許可權不會為 Web 應用程式開啟攝像頭

此處 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');
}

更新於: 29-Jan-2020

249 次瀏覽

開啟你的職業生涯

完成課程獲得認證

開始
廣告
© . All rights reserved.