Last active
June 1, 2023 00:27
-
-
Save sampotts/4b388d2764f6a2a249a132a4cd9390ed to your computer and use it in GitHub Desktop.
A user script to toggle Reddit's dark mode automatically based on your system preferences
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Get the initial state | |
const query = window.matchMedia('(prefers-color-scheme: dark)'); | |
function toggleDarkMode(toggle = query.matches) { | |
// Open the menu | |
document.querySelector('#USER_DROPDOWN_ID[aria-expanded="false"]')?.click(); | |
// Get the wrapper item | |
const wrapper = Array.from(document.querySelectorAll('button')).find(({ innerText }) => innerText.toLowerCase() === 'dark mode'); | |
const checkbox = wrapper?.querySelector(`[aria-checked="${!toggle}"]`); | |
checkbox?.click(); | |
// Close the menu | |
document.querySelector('#USER_DROPDOWN_ID[aria-expanded="true"]')?.click(); | |
} | |
// Listen for changes | |
query.addEventListener('change', (event) => toggleDarkMode(event.matches)); | |
// Run when DOM parsed with a delay for React rendering | |
document.addEventListener("DOMContentLoaded", () => { | |
setTimeout(() => toggleDarkMode(), 200); | |
}); | |
// Run when visibility changes (e.g. switching tabs) | |
document.addEventListener("visibilitychange", () => { | |
if (document.visibilityState === "visible") { | |
toggleDarkMode(); | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment