Reddit Automatic Dark Mode

Switches Reddit cark mode on and off according to System Theme (if exposed by browser).

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

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

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

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

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

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

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

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

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

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

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

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

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

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

// ==UserScript==
// @name         Reddit Automatic Dark Mode
// @namespace    https://github.com/r0uv3n/
// @version      2024-03-02
// @description  Switches Reddit cark mode on and off according to System Theme (if exposed by browser).
// @author       Henry Ruben Fischer
// @match        *://*.reddit.com/*
// @icon         https://www.redditstatic.com/shreddit/assets/favicon/64x64.png
// @grant        none
// @license      MIT
// ==/UserScript==

// jshint esversion:11
(function() {
    'use strict';
    const getPreferredTheme = () => window?.matchMedia?.('(prefers-color-scheme:dark)')?.matches ? 'dark' : 'light';
    const darkModeToggle = document.getElementsByName("darkmode-switch-name")[0];
    const getRedditTheme = () => darkModeToggle.attributes["aria-checked"] ? 'dark' : 'light';
    const applyPreferredTheme = () => {
        if (getRedditTheme() != getPreferredTheme()) {
            darkModeToggle.click();
        }
    }
    window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change',applyPreferredTheme);
    // The above event listener is probably not applied on page load, so we do that manually once. Also we need to wait a bit since reddit seems to set the theme manually after a bit.
    setTimeout(applyPreferredTheme, 3000); //Two seconds will elapse and Code will execute.

})();