2024-09-10
当前为
// ==UserScript==
// @name Reddit - Auto Dark Mode
// @namespace Kyan Violentmonkey Scripts
// @match *://*.reddit.com/*
// @grant none
// @version 1.0.0
// @license MIT
// @author Kyan
// @description 2024-09-10
// ==/UserScript==
;(function () {
'use strict';
const is_dark = (ele) => ele.checked === true
const is_light = (ele) => ele.checked === false
const to_dark = (switch_ele) => { if (is_light(switch_ele)) switch_ele.click() }
const to_light = (switch_ele) => { if (is_dark(switch_ele)) switch_ele.click() }
const is_prefer_dark = () => window.matchMedia("(prefers-color-scheme: dark)").matches
const is_prefer_light = () => window.matchMedia("(prefers-color-scheme: light)").matches
const when_element_exist = (selector, callback) => {
let timer = window.setInterval(() => {
if (document.querySelectorAll(selector).length > 0) {
clearInterval(timer)
callback()
}
}, 1000)
window.setTimeout(() => clearInterval(timer), 15000)
}
const theme_switch_selector = "faceplate-switch-input[name='darkmode-switch-name']"
when_element_exist(theme_switch_selector, () => {
// Find elements that needed
var theme_switch = document.querySelector(theme_switch_selector)
if (theme_switch === null) {
console.error(`Connot find ${theme_switch_selector} element`)
return
}
if (is_dark(theme_switch) && is_prefer_light()) {
to_light(theme_switch)
} else if (is_light(theme_switch) && is_prefer_dark()) {
to_dark(theme_switch)
} else {
console.log(`[Auto Dark Mode] Prefer: ${is_prefer_light()?"✓":"✗"}Light, ${is_prefer_dark()?"✓":"✗"}Dark`)
console.log(`[Auto Dark Mode] Current: ${is_light(theme_switch)?"✓":"✗"}Light, ${is_dark(theme_switch)?"✓":"✗"}Dark`)
}
})
})()