Reddit Theme Cookie Modifier

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

目前為 2025-11-17 提交的版本,檢視 最新版本

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

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

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

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

你需要先安裝一款使用者腳本管理器擴展,比如 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;
    });

})();