Reddit Theme Cookie Modifier

Modify the `theme` value inside the cookie so reddit can switch dark mode automatically

当前为 2025-11-17 提交的版本,查看 最新版本

您需要先安装一个扩展,例如 篡改猴Greasemonkey暴力猴,之后才能安装此脚本。

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

您需要先安装一个扩展,例如 篡改猴暴力猴,之后才能安装此脚本。

您需要先安装一个扩展,例如 篡改猴Userscripts ,之后才能安装此脚本。

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

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

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

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

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

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

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

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

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

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

// ==UserScript==
// @name         Reddit Theme Cookie Modifier
// @namespace    http://tampermonkey.net/
// @version      0.13
// @description  Modify the `theme` value inside the cookie so reddit can switch dark mode automatically
// @author       Orthon Jiang
// @match        *://*.reddit.com/*
// @icon         https://www.reddit.com/favicon.ico
// @grant        none
// @license      MIT
// ==/UserScript==

(function () {
    'use strict';

    // domains to try (order matters: parent domain first)
    const domains = ['.reddit.com', 'reddit.com', 'www.reddit.com'];

    // 设置一个长期过期时间(例如 1 年)
    function futureExpires(days = 365) {
        const d = new Date(Date.now() + days * 24 * 60 * 60 * 1000);
        return d.toUTCString();
    }

    // 立即删除(设置为过期)并重新写入 theme=0(覆盖同名 cookie)
    function replaceThemeOnDomain(domain) {
        try {
            // 先删除(写入过期时间)
            document.cookie = `theme=; domain=${domain}; path=/; expires=Thu, 01 Jan 1970 00:00:00 GMT`;
        } catch (e) {
            // ignore
        }
        try {
            // 再写入期望值(长期有效)
            document.cookie = `theme=0; domain=${domain}; path=/; expires=${futureExpires()}; Secure`;
        } catch (e) {
            // ignore
        }
    }

    // 一次性执行替换(父域优先)
    function applyOnce() {
        for (const d of domains) {
            replaceThemeOnDomain(d);
        }
    }

    // 轮询检测(站点可能会在运行时改回去)
    let lastCookieSnapshot = document.cookie;
    function pollAndFix() {
        const cur = document.cookie;
        if (cur !== lastCookieSnapshot) {
            // cookie 改变了 → 重新修正所有域
            applyOnce();
            lastCookieSnapshot = document.cookie;
        }
    }

    // 初次运行尽快生效
    applyOnce();

    // 轮询每 1500ms 检测并修正(如果你想更强力可调小间隔,但不要太频繁)
    const intervalId = setInterval(pollAndFix, 1500);

    // 额外:在页面完全载入后再确保一次
    window.addEventListener('load', () => {
        applyOnce();
        lastCookieSnapshot = document.cookie;
    });

})();