GM Fetch

A fetch API of GM_xmlhttpRequest

目前為 2023-08-16 提交的版本,檢視 最新版本

此腳本不應該直接安裝,它是一個供其他腳本使用的函式庫。欲使用本函式庫,請在腳本 metadata 寫上: // @require https://update.cn-greasyfork.org/scripts/472236/1235995/GM%20Fetch.js

您需要先安裝使用者腳本管理器擴展,如 TampermonkeyGreasemonkeyViolentmonkey 之後才能安裝該腳本。

You will need to install an extension such as Tampermonkey to install this script.

您需要先安裝使用者腳本管理器擴充功能,如 TampermonkeyViolentmonkey 後才能安裝該腳本。

您需要先安裝使用者腳本管理器擴充功能,如 TampermonkeyUserscripts 後才能安裝該腳本。

你需要先安裝一款使用者腳本管理器擴展,比如 Tampermonkey,才能安裝此腳本

您需要先安裝使用者腳本管理器擴充功能後才能安裝該腳本。

(我已經安裝了使用者腳本管理器,讓我安裝!)

你需要先安裝一款使用者樣式管理器擴展,比如 Stylus,才能安裝此樣式

你需要先安裝一款使用者樣式管理器擴展,比如 Stylus,才能安裝此樣式

你需要先安裝一款使用者樣式管理器擴展,比如 Stylus,才能安裝此樣式

你需要先安裝一款使用者樣式管理器擴展後才能安裝此樣式

你需要先安裝一款使用者樣式管理器擴展後才能安裝此樣式

你需要先安裝一款使用者樣式管理器擴展後才能安裝此樣式

(我已經安裝了使用者樣式管理器,讓我安裝!)

// ==UserScript==
// @name         GM Fetch
// @namespace    https://github.com/Sec-ant/gm-fetch
// @version      0.0.9
// @author       Ze-Zheng Wu
// @description  A fetch API of GM_xmlhttpRequest
// @license      MIT
// @homepage     https://github.com/Sec-ant/gm-fetch
// @homepageURL  https://github.com/Sec-ant/gm-fetch
// @source       https://github.com/Sec-ant/gm-fetch.git
// @supportURL   https://github.com/Sec-ant/gm-fetch/issues
// @match        *://*/*
// @grant        GM_xmlhttpRequest
// ==/UserScript==

(function () {
  'use strict';

  (function(global, factory) {
    typeof exports === "object" && typeof module !== "undefined" ? module.exports = factory() : typeof define === "function" && define.amd ? define(factory) : (global = typeof globalThis !== "undefined" ? globalThis : global || self, global.gmFetch = factory());
  })(globalThis, function() {
    var _GM_xmlhttpRequest = /* @__PURE__ */ (() => typeof GM_xmlhttpRequest != "undefined" ? GM_xmlhttpRequest : void 0)();
    function parseHeaders(rawHeaders) {
      const headers = new Headers();
      const preProcessedHeaders = rawHeaders.replace(/\r?\n[\t ]+/g, " ");
      preProcessedHeaders.split(/\r?\n/).forEach(function(line) {
        var _a;
        var parts = line.split(":");
        var key = (_a = parts.shift()) == null ? void 0 : _a.trim();
        if (key) {
          var value = parts.join(":").trim();
          try {
            headers.append(key, value);
          } catch (error) {
            console.warn("Response " + error.message);
          }
        }
      });
      return headers;
    }
    const gmFetch = async function(input, init) {
      if (typeof _GM_xmlhttpRequest !== "function") {
        throw new DOMException("GM_xmlhttpRequest not granted.", "NotFoundError");
      }
      const request = new Request(input, init);
      if (request.signal.aborted) {
        throw new DOMException("Network request aborted.", "AbortError");
      }
      const dataBuffer = await request.arrayBuffer();
      const data = dataBuffer.byteLength ? new TextDecoder().decode(dataBuffer) : void 0;
      const headers = Object.fromEntries(request.headers);
      new Headers(init == null ? void 0 : init.headers).forEach((value, key) => {
        headers[key] = value;
      });
      return new Promise((resolve, reject) => {
        let settled = false;
        const responseBlobPromise = new Promise((resolveBlob) => {
          const { abort } = _GM_xmlhttpRequest({
            method: request.method.toUpperCase(),
            url: request.url || location.href,
            headers,
            data,
            redirect: request.redirect,
            binary: true,
            nocache: request.cache === "no-store",
            revalidate: request.cache === "reload",
            timeout: 3e5,
            responseType: _GM_xmlhttpRequest.RESPONSE_TYPE_STREAM ?? "blob",
            overrideMimeType: request.headers.get("Content-Type") ?? void 0,
            anonymous: request.credentials === "omit",
            onload: ({ response: responseBody }) => {
              if (settled) {
                resolveBlob(null);
                return;
              }
              resolveBlob(responseBody);
            },
            async onreadystatechange({
              readyState,
              responseHeaders,
              status,
              statusText,
              finalUrl,
              response: responseBody
            }) {
              if (readyState === XMLHttpRequest.DONE) {
                request.signal.removeEventListener("abort", abort);
              } else if (readyState !== XMLHttpRequest.HEADERS_RECEIVED) {
                return;
              }
              if (settled) {
                resolveBlob(null);
                return;
              }
              const response = new Response(
                responseBody instanceof ReadableStream ? responseBody : await responseBlobPromise,
                {
                  status,
                  statusText
                }
              );
              Object.defineProperties(response, {
                url: {
                  value: finalUrl
                },
                redirected: {
                  value: request.url !== finalUrl
                },
                type: {
                  value: "basic"
                },
                headers: {
                  value: parseHeaders(responseHeaders)
                }
              });
              resolve(response);
              settled = true;
            },
            onerror: ({ statusText, error }) => {
              reject(
                new TypeError(statusText || error || "Network request failed.")
              );
              resolveBlob(null);
            },
            ontimeout() {
              reject(new TypeError("Network request timeout."));
              resolveBlob(null);
            },
            onabort() {
              reject(new DOMException("Network request aborted.", "AbortError"));
              resolveBlob(null);
            }
          });
          request.signal.addEventListener("abort", abort);
        });
      });
    };
    return gmFetch;
  });

})();