Dark Mode

A userscript to enable dark mode by changing white elements to black and inverting the text color on all websites.

  1. // ==UserScript==
  2. // @name Dark Mode
  3. // @namespace http://tampermonkey.net/
  4. // @version 1.0
  5. // @description A userscript to enable dark mode by changing white elements to black and inverting the text color on all websites.
  6. // @match *://*/*
  7. // @author kiwv
  8. // @grant none
  9. // @license MIT
  10. // ==/UserScript==
  11.  
  12. (function() {
  13. 'use strict';
  14.  
  15. // Keep track of the dark mode state
  16. let isDarkMode = true;
  17.  
  18. // Apply dark mode initially
  19. applyDarkMode();
  20.  
  21. // Function to apply dark mode
  22. function applyDarkMode() {
  23. const elements = document.querySelectorAll('*');
  24. for (let i = 0; i < elements.length; i++) {
  25. const element = elements[i];
  26.  
  27. // Invert text color
  28. const color = window.getComputedStyle(element).color;
  29. const backgroundColor = window.getComputedStyle(element).backgroundColor;
  30.  
  31. if (isDarkMode) {
  32. // Invert text color and change white elements to black
  33. if (color !== 'rgba(0, 0, 0, 0)' && color !== 'transparent') {
  34. element.style.color = invertColor(color);
  35. }
  36. if (
  37. backgroundColor === 'rgb(255, 255, 255)' ||
  38. backgroundColor === 'rgba(255, 255, 255, 0)'
  39. ) {
  40. element.style.backgroundColor = '#000';
  41. }
  42. }
  43. }
  44.  
  45. // Toggle the document body background color
  46. document.body.style.backgroundColor = isDarkMode ? '#000' : '';
  47. }
  48.  
  49. // Helper function to invert color
  50. function invertColor(color) {
  51. const hexColor = colorToHex(color);
  52. const invertedHexColor = (Number(`0x1${hexColor}`) ^ 0xffffff)
  53. .toString(16)
  54. .substr(1);
  55. return `#${invertedHexColor}`;
  56. }
  57.  
  58. // Helper function to convert color to hex format
  59. function colorToHex(color) {
  60. const rgb = color.match(/\d+/g);
  61. return (
  62. ((1 << 24) | (rgb[0] << 16) | (rgb[1] << 8) | Number(rgb[2]))
  63. .toString(16)
  64. .slice(1)
  65. );
  66. }
  67. })();