HTML5 - CORS

跨域资源共享(CORS)是一种允许来自Web浏览器中其他域的受限资源的机制.

对于假设,如果单击在html5演示部分的 HTML5-视频播放器上.它会询问相机的许可.如果用户允许该权限,则只有它会打开相机,否则它不会打开相机用于Web应用程序.

发出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中的事件句柄

Sr.No. 事件处理程序&描述
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, 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 = 'http://www.IT屋.com';
   
   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();
}
本文链接:https://www.f2er.com/3188899.html