HTML5-CORS

Cross-origin resource sharing (CORS) Webブラウザの別のドメインから制限されたリソースを許可するメカニズムです。

たとえば、html5デモセクションでHTML5-ビデオプレーヤーをクリックするとします。カメラの許可を求めます。ユーザーが許可を許可した場合、それだけがカメラを開きます。そうでない場合、Webアプリケーション用にカメラを開きません。

CORSリクエストを行う

ここで、Chrome、Firefox、Opera、SafariはすべてXMLHttprequest2オブジェクトを使用し、InternetExplorerは同様のXDomainRequestオブジェクトであるオブジェクトを使用します。

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

CORSのイベントハンドル

シニア番号 イベントハンドラーと説明
1

onloadstart

リクエストを開始します

2

onprogress

データをロードして送信します

3

onabort

リクエストを中止する

4

onerror

リクエストが失敗しました

5

onload

ロードを正常に要求します

6

ontimeout

リクエストが完了する前にタイムアウトが発生しました

7

onloadend

リクエストが成功または失敗したとき

onloadまたはonerrorイベントの例

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

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

ハンドラーを使用したCORSの例

以下の例は、makeCorsRequest()と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();
}