Home | History | Annotate | Download | only in base
      1 <!DOCTYPE html>
      2 <!--
      3 Copyright (c) 2013 The Chromium Authors. All rights reserved.
      4 Use of this source code is governed by a BSD-style license that can be
      5 found in the LICENSE file.
      6 -->
      7 
      8 <link rel="import" href="/base/base.html">
      9 
     10 <script>
     11 'use strict';
     12 
     13 tr.exportTo('tr.b', function() {
     14   function guessBinary(url) {
     15     return /[.]gz$/.test(url) || /[.]zip$/.test(url);
     16   }
     17   function get(url, async) {
     18     var req = new XMLHttpRequest();
     19     req.overrideMimeType('text/plain; charset=x-user-defined');
     20     req.open('GET', url, async);
     21     var isBinary = guessBinary(url);
     22     if (isBinary && async)
     23       req.responseType = 'arraybuffer';
     24 
     25     if (!async) {
     26       req.send(null);
     27       if (req.status == 200) {
     28         return req.responseText;
     29       } else {
     30         throw new Error('XHR failed with status ' + req.status);
     31       }
     32     }
     33 
     34     var p = new Promise(function(resolve, reject) {
     35       req.onreadystatechange = function(aEvt) {
     36         if (req.readyState == 4) {
     37           window.setTimeout(function() {
     38             if (req.status == 200) {
     39               resolve(isBinary ? req.response : req.responseText);
     40             } else {
     41               reject(new Error('XHR failed with status ' + req.status));
     42             }
     43           }, 0);
     44         }
     45       };
     46     });
     47     req.send();
     48     return p;
     49   }
     50 
     51   function getAsync(url) {
     52     if (!tr.isHeadless)
     53       return get(url, true);
     54     var filename = global.hrefToAbsolutePath(url);
     55     var isBinary = guessBinary(url);
     56     return Promise.resolve().then(function() {
     57       if (isBinary)
     58         return readbuffer(filename);
     59       return read(filename);
     60     });
     61   }
     62 
     63   function getSync(url) {
     64     if (!tr.isHeadless)
     65       return get(url, false);
     66     var filename = global.hrefToAbsolutePath(url);
     67     var isBinary = guessBinary(url);
     68     if (isBinary)
     69       return readbuffer(filename);
     70     return read(filename);
     71   }
     72 
     73   return {
     74     getAsync: getAsync,
     75     getSync: getSync
     76   };
     77 });
     78 </script>
     79