Computer >> Máy Tính >  >> Lập trình >> Javascript

CORS trong HTML5

Chia sẻ tài nguyên nhiều nguồn gốc (CORS) là một cơ chế cho phép các tài nguyên bị hạn chế từ một miền khác trong trình duyệt web

Giả sử, nếu bạn nhấp vào trình phát video HTML5 trong các phần trình diễn html5. nó sẽ yêu cầu sự cho phép của máy ảnh. nếu người dùng cho phép quyền thì chỉ nó mới mở máy ảnh hoặc nếu không nó sẽ không mở máy ảnh cho các ứng dụng web

Ở đây, Chrome, Firefox, Opera và Safari đều sử dụng đối tượng XMLHttprequest2 và Internet Explorer sử dụng đối tượng XDomainRequest tương tự.

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