Apply Binarize Filter to Any Page

Inject and apply thread filter to the body of any webpage

  1. // ==UserScript==
  2. // @name Apply Binarize Filter to Any Page
  3. // @namespace http://tampermonkey.net/
  4. // @version 0.2
  5. // @description Inject and apply thread filter to the body of any webpage
  6. // @author hatrd
  7. // @match *://*/*
  8. // @grant GM_getValue
  9. // @grant GM_setValue
  10. // @grant GM_registerMenuCommand
  11. // @run-at document-end
  12. // @license MIT
  13. // ==/UserScript==
  14.  
  15. (function() {
  16. 'use strict';
  17.  
  18. // 获取当前滤镜反转状态
  19. var filterInverted = GM_getValue('filterInverted', false);
  20.  
  21. // 创建 SVG 和 filter 元素
  22. var svgHtml = `
  23. <svg id="filterSvg" height="0" style="position:absolute; width:0; height:0">
  24. <filter id="normalThreshold">
  25. <feColorMatrix type="matrix" values="0.21 0.72 0.07 0 0
  26. 0.21 0.72 0.07 0 0
  27. 0.21 0.72 0.07 0 0
  28. 0 0 0 1 0" />
  29. <feComponentTransfer>
  30. <feFuncR type="discrete" tableValues="0 1" />
  31. <feFuncG type="discrete" tableValues="0 1" />
  32. <feFuncB type="discrete" tableValues="0 1" />
  33. </feComponentTransfer>
  34. </filter>
  35. <filter id="invertedThreshold">
  36. <feColorMatrix type="matrix" values="0.21 0.72 0.07 0 0
  37. 0.21 0.72 0.07 0 0
  38. 0.21 0.72 0.07 0 0
  39. 0 0 0 1 0" />
  40. <feComponentTransfer>
  41. <feFuncR type="discrete" tableValues="1 0" />
  42. <feFuncG type="discrete" tableValues="1 0" />
  43. <feFuncB type="discrete" tableValues="1 0" />
  44. </feComponentTransfer>
  45. </filter>
  46. </svg>
  47. `;
  48.  
  49. // 将 SVG 插入页面中
  50. document.body.insertAdjacentHTML('beforeend', svgHtml);
  51.  
  52. // 应用滤镜到 body
  53. applyFilter();
  54.  
  55. // 注册菜单命令以切换滤镜反转
  56. GM_registerMenuCommand("Toggle Filter Inversion", function() {
  57. filterInverted = !filterInverted;
  58. GM_setValue('filterInverted', filterInverted); // 更新存储的状态
  59. applyFilter(); // 应用新的滤镜
  60. }, "t");
  61.  
  62. function applyFilter() {
  63. // 根据 filterInverted 的值选择使用哪一个滤镜
  64. document.body.style.filter = filterInverted ? 'url(#invertedThreshold)' : 'url(#normalThreshold)';
  65. }
  66. })();