Modify the `theme` value inside the cookie so reddit can switch dark mode automatically
目前為
// ==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;
});
})();