dark mode

auto dark mode

  1. // ==UserScript==
  2. // @name dark mode
  3. // @namespace http://tampermonkey.net/
  4. // @version 2025-05-09
  5. // @description auto dark mode
  6. // @author Anc
  7. // @match *://*/*
  8. // @icon data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==
  9. // @run-at document.start
  10. // @grant GM.addStyle
  11. // @license MIT
  12. // ==/UserScript==
  13.  
  14. (function() {
  15. 'use strict';
  16.  
  17. // Add meta tag
  18. let meta = document.createElement('meta');
  19. meta.name = "theme-color";
  20. meta.content = "#000";
  21. meta.media = "(prefers-color-scheme: dark)";
  22. document.head.append(meta);
  23.  
  24. function isDarkColor(rgbString) {
  25. const match = rgbString.match(/\d+/g);
  26. if (!match || match.length < 3) return false; // 非 RGB 格式视为浅色或无法判断
  27. const [r, g, b] = match.map(Number);
  28. const brightness = 0.299 * r + 0.587 * g + 0.114 * b;
  29. return brightness < 128;
  30. }
  31.  
  32. function getEffectiveBackgroundColor(element) {
  33. while (element) {
  34. const style = window.getComputedStyle(element);
  35. const bgColor = style.backgroundColor;
  36. const bgImage = style.backgroundImage;
  37.  
  38. if (bgImage && bgImage !== 'none') {
  39. console.log('背景图:', bgImage);
  40. return 'image'; // 有背景图,视为特殊处理
  41. }
  42.  
  43. if (bgColor && bgColor !== 'rgba(0, 0, 0, 0)' && bgColor !== 'transparent') {
  44. return bgColor;
  45. }
  46.  
  47. element = element.parentElement;
  48. }
  49. return 'rgb(255, 255, 255)'; // 默认白色
  50. }
  51.  
  52. function checkIfBackgroundIsDark() {
  53. const targets = [document.body, document.documentElement];
  54. for (const el of targets) {
  55. const result = getEffectiveBackgroundColor(el);
  56. if (result === 'image') {
  57. console.log('无法判断背景图颜色,请人工确认');
  58. return false;
  59. }
  60. if (isDarkColor(result)) {
  61. console.log('背景是深色');
  62. return true;
  63. }
  64. }
  65. console.log('背景是浅色');
  66. return false;
  67. }
  68.  
  69. let isDark = checkIfBackgroundIsDark();
  70.  
  71. if(!isDark) {
  72. // Add style
  73. GM.addStyle(`
  74. @media (prefers-color-scheme: dark) {
  75. :root {
  76. filter: invert(1) hue-rotate(180deg);
  77. }
  78. figure,img,video,iframe,div[style*=image]{
  79. filter: invert(1) hue-rotate(180deg);
  80. opacity:1;
  81. }
  82.  
  83. figure img {
  84. filter: unset;
  85. }
  86. }
  87. `)
  88. }
  89. })();

QingJ © 2025

镜像随时可能失效,请加Q群300939539或关注我们的公众号极客氢云获取最新地址