HTML5 - CORS

Cross-origin resource sharing (CORS) è un meccanismo per consentire le risorse limitate da un altro dominio nel browser web.

Supponiamo, se fai clic su HTML5- video player nelle sezioni demo html5. chiederà il permesso della fotocamera. se l'utente consente l'autorizzazione, solo aprirà la fotocamera oppure non aprirà la fotocamera per le applicazioni web.

Effettuare una richiesta CORS

Qui Chrome, Firefox, Opera e Safari utilizzano tutti l'oggetto XMLHttprequest2 e Internet Explorer utilizza l'oggetto, oggetto XDomainRequest simile.

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

Maniglie degli eventi in CORS

Sr.No. Gestore e descrizione dell'evento
1

onloadstart

Avvia la richiesta

2

onprogress

Carica i dati e invia i dati

3

onabort

Annulla la richiesta

4

onerror

richiesta non riuscita

5

onload

richiesta di caricamento con successo

6

ontimeout

il timeout è scaduto prima che la richiesta potesse essere completata

7

onloadend

Quando la richiesta è completa o riuscita o non riuscita

Esempio di evento onload o onerror

xhr.onload = function() {
   var responseText = xhr.responseText;
   
   // process the response.
   console.log(responseText);
};

xhr.onerror = function() {
   console.log('There was an error!');
};

Esempio di CORS con gestore

L'esempio seguente mostrerà l'esempio di makeCorsRequest () e del gestore 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, 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;
}

// 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();
}