accept xhr options in download(url, options)

This commit is contained in:
tophf 2017-11-24 22:30:39 +03:00
parent 74e6ea5a56
commit 03048ea98e

View File

@ -408,49 +408,42 @@ function deleteStyleSafe({id, notify = true} = {}) {
} }
function download(url) { function download(url, {
method = url.includes('?') ? 'POST' : 'GET',
headers = {
'Content-type': 'application/x-www-form-urlencoded',
},
body = url.includes('?') ? url.slice(url.indexOf('?')) : null,
timeout = 10e3,
requiredStatusCode = 200,
} = {}) {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
url = new URL(url); url = new URL(url);
const TIMEOUT = 10000;
const options = {
method: url.search ? 'POST' : 'GET',
body: url.search ? url.search.slice(1) : null,
headers: {
'Content-type': 'application/x-www-form-urlencoded'
}
};
if (url.protocol === 'file:' && FIREFOX) { if (url.protocol === 'file:' && FIREFOX) {
// https://stackoverflow.com/questions/42108782/firefox-webextensions-get-local-files-content-by-path // https://stackoverflow.com/questions/42108782/firefox-webextensions-get-local-files-content-by-path
options.mode = 'same-origin';
// FIXME: add FetchController when it is available. // FIXME: add FetchController when it is available.
// https://developer.mozilla.org/en-US/docs/Web/API/FetchController/abort const timer = setTimeout(() => {
let timer; reject(new Error(`Fetch URL timeout: ${url.href}`));
}, timeout);
fetch(url.href, {mode: 'same-origin'}) fetch(url.href, {mode: 'same-origin'})
.then(r => { .then(r => {
clearTimeout(timer); clearTimeout(timer);
if (r.status !== 200) { return r.status === 200 ? r.text() : Promise.reject(r.status);
throw r.status;
}
return r.text();
}) })
.then(resolve, reject); .catch(reject)
timer = setTimeout( .then(resolve);
() => reject(new Error(`Fetch URL timeout: ${url.href}`)),
TIMEOUT
);
return; return;
} }
const xhr = new XMLHttpRequest(); const xhr = new XMLHttpRequest();
xhr.timeout = TIMEOUT; xhr.timeout = timeout;
xhr.onload = () => (xhr.status === 200 || url.protocol === 'file:' xhr.onload = () => (
? resolve(xhr.responseText) !requiredStatusCode || xhr.status === requiredStatusCode || url.protocol === 'file:' ?
: reject(xhr.status)); resolve(xhr.responseText) :
reject(xhr.status));
xhr.onerror = reject; xhr.onerror = reject;
xhr.open(options.method, url.href, true); xhr.open(method, url.href, true);
for (const key of Object.keys(options.headers)) { Object.keys(headers || {}).forEach(name => xhr.setRequestHeader(name, headers[name]));
xhr.setRequestHeader(key, options.headers[key]); xhr.send(body);
}
xhr.send(options.body);
}); });
} }