How to allow the restricted resources from another domain in web browser with HTML5


Cross-origin resource sharing (CORS) is a mechanism to allows the restricted resources from another domain in a web browser

For suppose, if you click on HTML5- video player in html5 demo sections. it will ask camera permission. if user allows the permission then only it will open the camera or else it doesn't open the camera for web applications

Here Chrome, Firefox, Opera and Safari all use the XMLHttprequest2 object and Internet Explorer uses the similar XDomainRequest object, 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');
}

Updated on: 29-Jan-2020

212 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements