gmfetch

A shim for using GM.xmlHttpRequest with a fetch-like API.

This script should not be not be installed directly. It is a library for other scripts to include with the meta directive // @require https://greasyfork.org/scripts/422172-gmfetch/code/gmfetch.js?version=903521

// ==UserScript==
// @name        gmfetch
// @author      matthin
// @namespace   https://github.com/matthin
// @version     1.0
// @license     GPL-3.0
// @description A shim for using GM.xmlHttpRequest with a fetch-like API.
// ==/UserScript==

function gmfetch(url) {
  return new Promise(resolve => {
    GM.xmlHttpRequest({
      url: url,
      onload: res => {
        const headers = new Headers();
        res.responseHeaders.trim().split('\n').forEach(line => {
          const [key, value] = line.split(': ');
          headers.append(key, value);
        });
        
        resolve(new Response(res.responseText, {
          status: res.status,
          statusText: res.statusText,
          headers: headers
        }));
      }
    });
  });
}