Last active
May 3, 2021 05:18
-
-
Save skoshy/a37a410e0bea5b8676d7987a275f3664 to your computer and use it in GitHub Desktop.
GM_fetch
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
/*********** | |
This is not a 100% 1:1 mapping to fetch, | |
but it works good enough for most use cases! | |
How to use: | |
Just copy and paste this function into your Userscript. | |
Then, call it as you would normal `fetch`. | |
************/ | |
async function GM_fetch(url, options = {}) { | |
return new Promise(resolve => { | |
GM_xmlhttpRequest({ | |
...options, | |
headers: { | |
'Content-Type': 'application/json', | |
...(options.headers || {}) | |
}, | |
url, | |
data: options.body, | |
onerror: () => throw new Error('Error'), | |
ontimeout: () => throw new Error('Timeout'), | |
onload: (xhr) => { | |
xhr.json = function() { | |
const xhrThis = this; | |
const jsonPromise = new Promise(resolve => { | |
let parsed; | |
try { | |
parsed = JSON.parse(xhrThis.responseText); | |
} catch(e) { | |
throw new Error('Could not JSON decode'); | |
} | |
resolve(parsed); | |
}); | |
return jsonPromise; | |
} | |
resolve(xhr); | |
}, | |
}); | |
}); | |
}; | |
/*************** | |
How to use it | |
****************/ | |
const resp = await GM_fetch('https://xxxxx.com', { | |
method: 'POST', | |
headers: { | |
'api-key': 'xxxxxxxxxxxxxxxxxxxx', | |
}, | |
body: JSON.stringify(body), | |
}); | |
const decoded = await resp.json(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This definitely is not a 100% 1:1 mapping to
fetch
, but it works good enough in Greasemonkey / Tampermonkey / Violentmonkey scripts. Great for making requests to bypass CORS.Remember to add this to your script header in order for it to work
// @grant GM_xmlhttpRequest
Feel free to leave comments/suggestions for improvement.