blob: b8954d8317139f96d329865c60cbf0466ce53fdc [file] [log] [blame]
<!DOCTYPE html>
<!--
Copyright (c) 2013 The Chromium Authors. All rights reserved.
Use of this source code is governed by a BSD-style license that can be
found in the LICENSE file.
-->
<link rel="import" href="/tracing/base/base.html">
<script>
'use strict';
tr.exportTo('tr.b', function() {
function guessBinary(url) {
return /[.]gz$/.test(url) || /[.]zip$/.test(url);
}
function xhr(method, url, async, opt_data) {
var req = new XMLHttpRequest();
req.overrideMimeType('text/plain; charset=x-user-defined');
req.open(method, url, async);
var isBinary = guessBinary(url);
if (isBinary && async)
req.responseType = 'arraybuffer';
var data = opt_data !== undefined ? opt_data : null;
if (!async) {
req.send(data);
if (req.status == 200) {
return req.responseText;
} else {
throw new Error('XHR failed with status ' + req.status);
}
}
var p = new Promise(function(resolve, reject) {
req.onreadystatechange = function(aEvt) {
if (req.readyState == 4) {
window.setTimeout(function() {
if (req.status == 200) {
if (req.responseType === 'arraybuffer')
return resolve(req.response);
return resolve(req.responseText);
} else {
reject(new Error('XHR failed with status ' + req.status));
}
}, 0);
}
};
});
req.send(data);
return p;
}
function getAsync(url) {
if (!tr.isHeadless)
return xhr('GET', url, true);
var filename;
if (url.startsWith('file:///'))
filename = url.substring(7);
else
filename = global.hrefToAbsolutePath(url);
var isBinary = guessBinary(url);
return Promise.resolve().then(function() {
if (isBinary)
return readbuffer(filename);
return read(filename);
});
}
function getSync(url) {
if (!tr.isHeadless)
return xhr('GET', url, false);
var filename;
if (url.startsWith('file:///'))
filename = url.substring(7);
else
filename = global.hrefToAbsolutePath(url);
var isBinary = guessBinary(url);
if (isBinary)
return readbuffer(filename);
return read(filename);
}
function postAsync(url, data) {
if (tr.isHeadless)
throw new Error('Only supported inside a browser');
return xhr('POST', url, true, data);
}
return {
getAsync: getAsync,
getSync: getSync,
postAsync: postAsync
};
});
</script>