Greasy Fork

Greasy Fork is available in English.

添加自定义Header

尝试在请求中添加自定义Header

您需要先安装一款用户脚本管理器扩展,例如 Tampermonkey 篡改猴Greasemonkey 油猴子Violentmonkey 暴力猴,才能安装此脚本。

您需要先安装一款用户脚本管理器扩展,例如 Tampermonkey 篡改猴,才能安装此脚本。

您需要先安装一款用户脚本管理器扩展,例如 Tampermonkey 篡改猴Violentmonkey 暴力猴,才能安装此脚本。

您需要先安装一款用户脚本管理器扩展,例如 Tampermonkey 篡改猴Userscripts ,才能安装此脚本。

您需要先安装一款用户脚本管理器扩展,例如 Tampermonkey 篡改猴,才能安装此脚本。

您需要先安装一款用户脚本管理器扩展后才能安装此脚本。

(我已经安装了用户脚本管理器,让我安装!)

您需要先安装一款用户样式管理器扩展,比如 Stylus,才能安装此样式。

您需要先安装一款用户样式管理器扩展,比如 Stylus,才能安装此样式。

您需要先安装一款用户样式管理器扩展,比如 Stylus,才能安装此样式。

您需要先安装一款用户样式管理器扩展后才能安装此样式。

您需要先安装一款用户样式管理器扩展后才能安装此样式。

您需要先安装一款用户样式管理器扩展后才能安装此样式。

(我已经安装了用户样式管理器,让我安装!)

// ==UserScript==
// @name         添加自定义Header
// @namespace    http://tampermonkey.net/
// @version      0.2
// @description  尝试在请求中添加自定义Header
// @author       你的名字
// @match        *://*/*
// @grant        none
// @license MIT
// ==/UserScript==

(function() {
    'use strict';

    // 修改 XMLHttpRequest
    const originalOpen = XMLHttpRequest.prototype.open;
    XMLHttpRequest.prototype.open = function(method, url, async, user, password) {
        this.addEventListener('loadstart', function() {
            this.setRequestHeader('x-tt-env', 'boe_im');
        }, false);
        originalOpen.call(this, method, url, async, user, password);
    };

    // 修改 fetch
    const originalFetch = window.fetch;
    window.fetch = async function(input, init) {
        // 如果 init 对象已经存在,并且 headers 也是对象,则添加自定义 header
        if (init && typeof init.headers === 'object') {
            init.headers['x-tt-env'] = 'boe_im';
        } else {
            // 否则创建一个新的 headers 对象
            init = {
                ...init,
                headers: {
                    'x-tt-env': 'boe_im',
                    ...(init && init.headers ? init.headers : {}),
                },
            };
        }
        return originalFetch(input, init);
    };
})();