Skip to content

Instantly share code, notes, and snippets.

@w35l3y
Last active July 24, 2019 19:16
Show Gist options
  • Save w35l3y/365f535ba6f98dd69a8893fc614f367e to your computer and use it in GitHub Desktop.
Save w35l3y/365f535ba6f98dd69a8893fc614f367e to your computer and use it in GitHub Desktop.
fetch to gm
function fetch (url, { method = "GET", headers = {}, body = null } = {}) {
return new Promise((resolve, reject) => {
if ("GET" === method) {
if (body) {
url += "?" + body;
body = null;
}
delete headers["Content-Type"];
}
console.log(method, url, body, headers);
GM.xmlHttpRequest({
url,
method,
headers,
data: body,
onload: xhr => {
const { status, statusText, responseHeaders } = xhr;
const headers = new Headers();
responseHeaders.split("\r\n").forEach(v => {
if (/([^:]+):\s*(.+)/.test(v)) {
headers.append(RegExp.$1, RegExp.$2);
}
});
let body = xhr.response;
if (204 === status) {
body = null;
}
console.log("RESPONSE", status, statusText);
resolve(new window.Response(body, {
status,
statusText,
headers
}));
},
onerror: xhr => {
reject("ERROR");
},
ontimeout: xhr => {
reject("TIMEOUT");
},
onabort: xhr => {
reject("ABORT");
}
});
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment