// ==UserScript==
// @name        监控
// @namespace   Scripts
// @match       *://test23.adsdesk.cn/*
// @grant       none
// @version     1.0
// @author      -
// @description 2023/12/6 13:42:17
// ==/UserScript==

(function () {
    'use strict';
    console.log("begin")

    //region 监听HTTP请求
    //(function(){})(): 表示立即执行, 注册全局代理对象(防止重写XMLHttpRequest时循环调用?)
    ;(function () {
        if (typeof window.CustomEvent === "function") return false;

        function CustomEvent(event, params) {
            params = params || {bubbles: false, cancelable: false, detail: undefined};
            const evt = document.createEvent('CustomEvent');
            evt.initCustomEvent(event, params.bubbles, params.cancelable, params.detail);
            return evt;
        }

        CustomEvent.prototype = window.Event.prototype;

        window.CustomEvent = CustomEvent;
    })();
    // 重写 XMLHttpRequest 全局拦截器
    ;(function () {
        function ajaxEventTrigger(event) {
            const ajaxEvent = new CustomEvent(event, {detail: this});
            window.dispatchEvent(ajaxEvent);
        }

        const oldXHR = window.XMLHttpRequest;

        function newXHR() {
            const realXHR = new oldXHR();

            // abort, error, load, loadstart, progress, timeout, loadend 可按需重写, 此处仅需要readystatechange
            realXHR.addEventListener('readystatechange', function () {
                ajaxEventTrigger.call(this, 'ajaxReadyStateChange');
            }, false);

            let send = realXHR.send;
            realXHR.send = function (...arg) {
                send.apply(realXHR, arg);
                realXHR.body = arg[0];
                ajaxEventTrigger.call(realXHR, 'ajaxSend');
            }

            let open = realXHR.open;
            realXHR.open = function (...arg) {
                open.apply(realXHR, arg)
                realXHR.method = arg[0];
                realXHR.orignUrl = arg[1];
                realXHR.async = arg[2];
                ajaxEventTrigger.call(realXHR, 'ajaxOpen');
            }

            let setRequestHeader = realXHR.setRequestHeader;
            realXHR.requestHeader = {};
            realXHR.setRequestHeader = function (name, value) {
                realXHR.requestHeader[name] = value;
                setRequestHeader.call(realXHR, name, value)
            }
            return realXHR;
        }

        window.XMLHttpRequest = newXHR;
    })();
    //endregion

    window.addEventListener('ajaxReadyStateChange', function (e) {
        const xhr = e.detail;

        // 不放在onload里会执行多次3次(状态变更事件会触发3次)
        xhr.onload = function () {
            console.log('Request URL:', xhr.orignUrl);
            console.log('Request Body:', xhr.body);
        }
    })
    console.log("end")
})()
