Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

วิธีอนุญาตทรัพยากรที่ถูกจำกัดจากโดเมนอื่นในเบราว์เซอร์ด้วย HTML5


Cross-origin resource sharing (CORS) เป็นกลไกที่อนุญาตให้เข้าถึงทรัพยากรที่ถูกจำกัดจากโดเมนอื่นในเว็บเบราว์เซอร์

เช่น หากคุณคลิกที่ HTML5 video player ในส่วนสาธิต HTML5 จะขอสิทธิ์กล้อง หากผู้ใช้อนุญาต จึงจะเปิดกล้องได้ มิฉะนั้นจะไม่เปิดกล้องให้แอปพลิเคชันเว็บ

ที่นี่ Chrome, Firefox, Opera และ Safari ใช้วัตถุ XMLHttprequest2 และ Internet Explorer ใช้ XDomainRequest object

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