HTML5 Web CORS

Web CORS in HTML5 is used to access the restricted area of other domains in a web browser. In this tutorial, you can get a piece of detail knowledge on the following.

  • About CORS
  • Event handler
  • Browser Support

About HTML5 Web CORS

The CORS is popularly known as Cross-Origin Resources Sharing which allows sharing unauthorized areas of other domains in a web browser. For example, in case you click on any video player then it will ask permission to access the camera otherwise it doesn’t allow access.

HTML5 CORS Request

To make CORS Request XML HTTPrequest2 object is used for the chrome, firefox, Safari, Opera and XDomainRequest object is used in IE.

CORS Example

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

HTML5 Event Handler

The event handlers used to handle CORS in HTML5 and are listed below.

EVENT HANDLER DESCRIPTION
bad_alloc Occurs when a failure in memory allocation
onloadstart Used to start the request
bad_typeid Exception is thrown by typeid function
bad_function_call Exception is thrown when an empty function is called
onprogress Used to loads the data and send the data
onabort Used to abort the request
onerror used to action request has failed
onload Used to load successfully
ontimeout The request should complete before the timeout

To describe the onload or onerror events the following code will be helpful.

onload or onerror events Example

xhr.onload = function() {
var responseText = xhr.responseText;// process the response.
console.log(responseText);
};
xhr.onerror = function() {
console.log('There was an error!');
};

makeCorsRequest() and onload handler Example

The following example is used to define makeCorsRequest() and onload handler.

function createCORSRequest(method, url) {
var xhr = new XMLHttpRequest();
if ("withCredentials" in xhr) {
// XHR for Chrome/Firefox/Opera/Safari.
xhr.open(method, url, true);
}
else if (typeof XDomainRequest != "undefined") {
// XDomainRequest for IE.
xhr = new XDomainRequest();
xhr.open(method, url);
}
else {
// CORS not supported.
xhr = null;
}
return xhr;
}
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.tutorialspoint.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();
}

HTML5 Web CORS Browser Support

1. HTML5 Web CORS supported by most of all major and latest browsers.
2. Different types of requests are used for different browsers.
3. Restricted Resources are not allowed by CORS.