YouTube auto dark mode

Automatically switch the dark mode according to the system settings, which uses the official style

You will need to install an extension such as Tampermonkey, Greasemonkey or Violentmonkey to install this script.

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

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

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

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

You will need to install a user script manager extension to install this script.

(I already have a user script manager, let me install it!)

You will need to install an extension such as Stylus to install this style.

You will need to install an extension such as Stylus to install this style.

You will need to install an extension such as Stylus to install this style.

You will need to install a user style manager extension to install this style.

You will need to install a user style manager extension to install this style.

You will need to install a user style manager extension to install this style.

(I already have a user style manager, let me install it!)

// ==UserScript==
// @name         YouTube auto dark mode
// @version      1.0.0
// @description  Automatically switch the dark mode according to the system settings, which uses the official style
// @namespace    https://youtube.com/
// @match        https://www.youtube.com/*
// @icon         https://www.google.com/s2/favicons?sz=64&domain=youtube.com
// @author       bowencool
// @license      MIT
// @homepageURL  https://greasyfork.org/scripts/460040
// @supportURL   https://github.com/bowencool/Tampermonkey-Scripts/issues
// @grant        none
// ==/UserScript==

(function () {
  "use strict";

  window
    .matchMedia("(prefers-color-scheme: dark)")
    .addEventListener("change", (e) => {
      toggle(e.matches);
    });

  function toggle(
    isDarkMode = window.matchMedia("(prefers-color-scheme: dark)").matches
  ) {
    const currentTheme = document.querySelector("html").getAttribute("dark");
    console.log({ isDarkMode, currentTheme });
    if (isDarkMode) {
      if (currentTheme !== null) return;
      document.querySelector("html").setAttribute("dark", "");
    } else {
      if (currentTheme === null) return;
      document.querySelector("html").removeAttribute("dark");
    }
  }
})();