Global Selection Style

Set custom styles for text selection across all websites, only if not already defined

  1. // ==UserScript==
  2. // @name Global Selection Style
  3. // @namespace http://tampermonkey.net/
  4. // @version 1.0
  5. // @description Set custom styles for text selection across all websites, only if not already defined
  6. // @author jhll1124
  7. // @match *://*/*
  8. // @exclude *://www.bilibili.com/* // 排除B站
  9. // @grant GM_addStyle
  10. // @license MIT
  11. // ==/UserScript==
  12.  
  13. (function() {
  14. 'use strict';
  15.  
  16. const targetSelectors = [
  17. '::selection',
  18. '*::selection',
  19. 'body::selection',
  20. 'html::selection'
  21. ];
  22.  
  23. let found = false;
  24.  
  25. for (const sheet of document.styleSheets) {
  26. try {
  27. const rules = sheet.cssRules;
  28. if (!rules) continue;
  29.  
  30. for (const rule of rules) {
  31. if (rule.selectorText && targetSelectors.some(sel => rule.selectorText.includes(sel))) {
  32. found = true;
  33. break;
  34. }
  35. }
  36. } catch (e) {
  37. // 忽略跨域样式表
  38. }
  39. if (found) break;
  40. }
  41.  
  42. if (!found) {
  43. GM_addStyle(`
  44. ::selection {
  45. background-color: rgb(242, 198, 255);
  46. }
  47. `);
  48. }
  49. })();