Skip to content

Instantly share code, notes, and snippets.

@skoshy
Last active May 3, 2021 05:18
Show Gist options
  • Save skoshy/a37a410e0bea5b8676d7987a275f3664 to your computer and use it in GitHub Desktop.
Save skoshy/a37a410e0bea5b8676d7987a275f3664 to your computer and use it in GitHub Desktop.
GM_fetch
/***********
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();
@skoshy
Copy link
Author

skoshy commented May 3, 2021

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment