Toggle dark mode with Ctrl+Shift+D

Toggles dark mode with Ctrl+Shift+D.

  1. // ==UserScript==
  2. // @name Toggle dark mode with Ctrl+Shift+D
  3. // @namespace https://github.com/yookibooki/userscripts
  4. // @description Toggles dark mode with Ctrl+Shift+D.
  5. // @version 1.0
  6. // @match *://*/*
  7. // @grant GM_addStyle
  8. // @grant GM_getValue
  9. // @grant GM_setValue
  10. // ==/UserScript==
  11.  
  12. (function() {
  13. 'use strict';
  14.  
  15. const STORAGE_KEY = 'universal-dark-mode-enabled';
  16. const CSS_CLASS = 'universal-dark-mode-active';
  17.  
  18. GM_addStyle(`
  19. html {
  20. transition: filter 0.3s ease !important;
  21. min-height: 100vh !important;
  22. }
  23.  
  24. .${CSS_CLASS} img,
  25. .${CSS_CLASS} video,
  26. .${CSS_CLASS} iframe,
  27. .${CSS_CLASS} canvas {
  28. filter: invert(1) hue-rotate(180deg) !important;
  29. }
  30.  
  31. .${CSS_CLASS}::selection {
  32. background: #fff !important;
  33. color: #000 !important;
  34. }
  35. `);
  36.  
  37. function toggleDarkMode() {
  38. const html = document.documentElement;
  39. const isActive = html.classList.toggle(CSS_CLASS);
  40. GM_setValue(STORAGE_KEY, isActive);
  41. }
  42.  
  43. function handleShortcut(e) {
  44. if (e.ctrlKey && e.shiftKey && e.keyCode === 68) { // Ctrl+Shift+D
  45. toggleDarkMode();
  46. e.preventDefault();
  47. e.stopPropagation();
  48. }
  49. }
  50.  
  51. if (GM_getValue(STORAGE_KEY, false)) {
  52. document.documentElement.classList.add(CSS_CLASS);
  53. }
  54.  
  55. document.addEventListener('keydown', handleShortcut, true);
  56. const style = document.createElement('style');
  57. style.textContent = `
  58. .${CSS_CLASS} {
  59. filter: invert(1) hue-rotate(180deg) !important;
  60. background: #fff !important; /* Create inversion base */
  61. }
  62. `;
  63. document.head.appendChild(style);
  64. })();