Html5-cors

提供:Dev Guides
移動先:案内検索

HTML5-CORS

  • クロスオリジンリソース共有(CORS)*は、Webブラウザの別のドメインからの制限されたリソースを許可するメカニズムです。

たとえば、html5デモセクションで_HTML5- video player_をクリックするとします。 カメラの許可を求めます。 ユーザーが許可を許可すると、カメラのみが開かれるか、Webアプリケーションのカメラが開かなくなります。

CORSリクエストを行う

ここでは、Chrome、Firefox、Opera、およびSafariはすべてXMLHttprequest2オブジェクトを使用し、Internet Explorerは同様の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のイベントハンドル

Sr.No. Event Handler & Description
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.finddevguides.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();
}