油猴脚本求助!@grant 与 fetch冲突!【已解决】!

:sob:难受啊,大佬们帮俺看看

问题: : 一旦我加上 @grant GM_xmlhttpRequest 、 @grant GM_addStyle 任一一个,都是让fetch拦截失效!

注:

  1. @grant none 是可以的
  2. 代码中的 console.log(“wawaw”); 会打印,但是再往后,就没有后文了!

结构是这样的

重点代码:


// ==UserScript==
// @name       .....
....
// @grant        GM_xmlhttpRequest
// @grant        GM_addStyle
// @noframes
// ==/UserScript==


    function interceptNetworkRequests() {
        const originalXHROpen = XMLHttpRequest.prototype.open;
        XMLHttpRequest.prototype.open = function(method, url, ...args) {
            this.addEventListener('readystatechange', function() {
                // console.log("XHR",method,url);
                if (this.readyState === 4 && this.status === 200 && url.includes('/api/ec/dev/table/datas')) {
                    const dataKey = new URLSearchParams(this.responseURL).get('dataKey');
                    if (dataKey) {
                        displayDebugButton(dataKey);
                    }
                }
            });
            return originalXHROpen.apply(this, [method, url, ...args]);
        };

        const originalFetch = window.fetch;
        console.log("wawaw");
        window.fetch = function(resource, config) {
            console.log("aabbb",resource,"bbaaa",config);
            if (config && config.method === 'POST' && config.headers) {
                const params = new URLSearchParams(config.body);
                const dataKey = params.get('dataKey');
                if (dataKey) {
                    displayDebugButton(dataKey);
                }
            }

            return originalFetch.apply(this, arguments)
                .then(response => {
                console.log("response",response);
                if (response.url.includes('/api/ec/dev/table/datas') && response.status === 200) {
                    response.clone().text().then(text => {
                        const params = new URLSearchParams(text);
                        const dataKey = params.get('dataKey');
                        console.log("aaa");
                        if (dataKey) {
                            displayDebugButton(dataKey);
                        }
                    });
                }
                return response;
            });
        };
    }

    ...

    function main() {
    ...
        interceptNetworkRequests();
    }

   ...
1 个赞

帮顶

:sob:有没有大佬帮忙康康

佬们,通过claude了解到,应该是冲突了,现在已经放弃了GM_xmlhttpRequest和GM_addStyle,直接使用fetch了

From 快问快答 to 开发调优