如何透過 HTML5 允許不同域中的受限資源進入網路瀏覽器


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

假設您單擊 html5 演示部分中的 HTML5 影片播放器。它會詢問相機許可權。如果使用者允許許可權,則只打開相機,否則它不會為網頁應用程式開啟相機

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

更新於: 2020 年 1 月 29 日

248 次瀏覽

啟動您的職業

完成課程獲得認證

開始
廣告
© . All rights reserved.