XHR_Interceptor

XHR请求拦截工具类

目前為 2024-05-10 提交的版本,檢視 最新版本

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

// ==UserScript==
// @name         XHR_Interceptor
// @version      1.0.0
// @description  XHR请求拦截工具类
// @author       Zosah
// ==/UserScript==

class XMRHandler {
        constructor() {
            if (XMRHandler.instance) {
                return XMRHandler.instance;
            }
            this.interceptors = [];
            XMRHandler.instance = this;
        }

        addUrlInterceptor(item) {
            this.interceptors.push(item);
        }

        execute() {
            function xhrInterceptor(callback) {
                // send拦截
                let oldSend = null;
                // 在xhr函数下创建一个回调
                XMLHttpRequest.callbacks = function (xhr) {
                    //调用劫持函数,填入一个function的回调函数
                    //回调函数监听了对xhr调用了监听load状态,并且在触发的时候再次调用一个function,进行一些数据的劫持以及修改
                    xhr.addEventListener("load", function () {
                        if (xhr.readyState == 4 && xhr.status == 200) {
                            callback(xhr);
                        }
                    });
                };
                //获取xhr的send函数,并对其进行劫持
                oldSend = XMLHttpRequest.prototype.send;
                XMLHttpRequest.prototype.send = function () {
                    XMLHttpRequest.callbacks(this);
                    //由于我们获取了send函数的引用,并且复写了send函数,这样我们在调用原send的函数的时候,需要对其传入引用,而arguments是传入的参数
                    oldSend.apply(this, arguments);
                };
            }
            xhrInterceptor((xhr) => {
                for (const item of this.interceptors) {
                    const url = xhr.responseURL.split(item.domain)[1];
                    if (url === item.url) {
                        item.cb(JSON.parse(xhr.response));
                    }
                }
            });
        }
    }