Last active
July 24, 2019 19:16
-
-
Save w35l3y/365f535ba6f98dd69a8893fc614f367e to your computer and use it in GitHub Desktop.
fetch to gm
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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