Reddit Advanced Content Filter

Automatically hides posts and comments on Reddit based on keywords or subreddits you specify, with original config dialog styling restored.

当前为 2024-12-10 提交的版本,查看 最新版本

  1. // ==UserScript==
  2. // @name Reddit Advanced Content Filter
  3. // @namespace https://greasyfork.org/en/users/567951-stuart-saddler
  4. // @version 2.3
  5. // @description Automatically hides posts and comments on Reddit based on keywords or subreddits you specify, with original config dialog styling restored.
  6. // @author Stuart Saddler
  7. // @license MY
  8. // @icon https://clipart-library.com/images_k/smoke-clipart-transparent/smoke-clipart-transparent-6.png
  9. // @supportURL https://greasyfork.org/en/users/567951-stuart-saddler
  10. // @match *://www.reddit.com/*
  11. // @match *://old.reddit.com/*
  12. // @run-at document-end
  13. // @grant GM.getValue
  14. // @grant GM.setValue
  15. // @grant GM_addStyle
  16. // @grant GM_registerMenuCommand
  17. // @grant GM_unregisterMenuCommand
  18. // ==/UserScript==
  19.  
  20. (async function() {
  21. 'use strict';
  22.  
  23. const postSelector = 'article, div[data-testid="post-container"], shreddit-post';
  24. let filteredCount = 0;
  25. let menuCommand = null;
  26. let processedPosts = new WeakSet();
  27. let blocklistArray = [];
  28. let keywordPattern = null;
  29. let pendingUpdates = 0;
  30.  
  31. const batchUpdateCounter = debounce(() => {
  32. if (typeof GM_registerMenuCommand !== 'undefined') {
  33. if (menuCommand !== null) {
  34. GM_unregisterMenuCommand(menuCommand);
  35. }
  36. menuCommand = GM_registerMenuCommand(
  37. `Configure Blocklist (${filteredCount} blocked)`,
  38. showConfig
  39. );
  40. } else {
  41. createFallbackButton();
  42. }
  43. }, 16);
  44.  
  45. const cleanup = () => {
  46. if (pendingUpdates === 0) return;
  47. pendingUpdates = 0;
  48. batchUpdateCounter();
  49. };
  50.  
  51. setInterval(cleanup, 1000);
  52.  
  53. const CSS = `
  54. .content-filtered { display: none !important; height: 0 !important; overflow: hidden !important; }
  55. .reddit-filter-dialog { position: fixed; top: 50%; left: 50%; transform: translate(-50%, -50%); background: white; padding: 20px; border-radius: 8px; z-index: 1000000; box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15); min-width: 300px; max-width: 350px; font-family: Arial, sans-serif; color: #333; }
  56. .reddit-filter-dialog h2 { margin-top: 0; color: #0079d3; font-size: 1.5em; font-weight: bold; }
  57. .reddit-filter-dialog p { font-size: 0.9em; margin-bottom: 10px; color: #555; }
  58. .reddit-filter-dialog textarea { width: calc(100% - 16px); height: 150px; padding: 8px; margin: 10px 0; border: 1px solid #ccc; border-radius: 4px; font-family: monospace; background: #f9f9f9; color: #000; resize: vertical; }
  59. .reddit-filter-dialog .button-container { display: flex; justify-content: flex-end; gap: 10px; margin-top: 10px; }
  60. .reddit-filter-dialog button { display: flex; align-items: center; justify-content: center; padding: 8px 16px; border: none; border-radius: 4px; cursor: pointer; font-size: 1em; text-align: center; }
  61. .reddit-filter-dialog .save-btn { background-color: #0079d3; color: white; }
  62. .reddit-filter-dialog .cancel-btn { background-color: #f2f2f2; color: #333; }
  63. .reddit-filter-dialog button:hover { opacity: 0.9; }
  64. .reddit-filter-overlay { position: fixed; top: 0; left: 0; right: 0; bottom: 0; background: rgba(0, 0, 0, 0.5); z-index: 999999; }
  65. `;
  66.  
  67. if (typeof GM_addStyle !== 'undefined') {
  68. GM_addStyle(CSS);
  69. } else {
  70. const style = document.createElement('style');
  71. style.textContent = CSS;
  72. document.head.appendChild(style);
  73. }
  74.  
  75. const getKeywordPattern = (keywords) => {
  76. const escapedKeywords = keywords.map(k => k.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')).join('|');
  77. return new RegExp(`\\b(${escapedKeywords})(s|es|ies)?\\b`, 'i');
  78. };
  79.  
  80. async function showConfig() {
  81. const overlay = document.createElement('div');
  82. overlay.className = 'reddit-filter-overlay';
  83. const dialog = document.createElement('div');
  84. dialog.className = 'reddit-filter-dialog';
  85. dialog.innerHTML = `
  86. <h2>Reddit Filter: Blocklist</h2>
  87. <p>Enter keywords or subreddit names one per line. Filtering is case-insensitive.</p>
  88. <p><em>Keywords can match common plural forms (e.g., "apple" blocks "apples"). Irregular plurals (e.g., "mouse" and "mice") must be added separately. Subreddit names should be entered without the "r/" prefix (e.g., "subredditname").</em></p>
  89. <textarea spellcheck="false" id="blocklist">${blocklistArray.join('\n')}</textarea>
  90. <div class="button-container">
  91. <button class="cancel-btn">Cancel</button>
  92. <button class="save-btn">Save</button>
  93. </div>
  94. `;
  95.  
  96. document.body.appendChild(overlay);
  97. document.body.appendChild(dialog);
  98.  
  99. const closeDialog = () => {
  100. dialog.remove();
  101. overlay.remove();
  102. };
  103.  
  104. dialog.querySelector('.save-btn').addEventListener('click', async () => {
  105. const blocklistInput = dialog.querySelector('#blocklist').value;
  106. blocklistArray = blocklistInput
  107. .split('\n')
  108. .map(item => item.trim().toLowerCase())
  109. .filter(item => item.length > 0);
  110. keywordPattern = getKeywordPattern(blocklistArray);
  111. await GM.setValue('blocklist', blocklistArray);
  112. closeDialog();
  113. location.reload();
  114. });
  115.  
  116. dialog.querySelector('.cancel-btn').addEventListener('click', closeDialog);
  117. overlay.addEventListener('click', closeDialog);
  118. }
  119.  
  120. function createFallbackButton() {
  121. const button = document.createElement('button');
  122. button.innerHTML = `Configure Blocklist (${filteredCount} blocked)`;
  123. button.style.cssText = 'position:fixed;top:10px;right:10px;z-index:999999;padding:8px;';
  124. button.addEventListener('click', showConfig);
  125. document.body.appendChild(button);
  126. }
  127.  
  128. async function processPostsBatch(posts) {
  129. const batchSize = 5;
  130. for (let i = 0; i < posts.length; i += batchSize) {
  131. const batch = posts.slice(i, i + batchSize);
  132. await new Promise(resolve => requestIdleCallback(resolve, { timeout: 1000 }));
  133. batch.forEach(post => processPost(post));
  134. }
  135. }
  136.  
  137. function processPost(post) {
  138. if (!post || processedPosts.has(post)) return;
  139. processedPosts.add(post);
  140.  
  141. let shouldHide = false;
  142. const subredditElement = post.querySelector('a[data-click-id="subreddit"], a.subreddit');
  143.  
  144. if (subredditElement) {
  145. const subredditName = subredditElement.textContent.trim().replace(/^r\//i, '').toLowerCase();
  146. if (blocklistArray.includes(subredditName)) {
  147. shouldHide = true;
  148. }
  149. }
  150.  
  151. if (!shouldHide && blocklistArray.length > 0) {
  152. const postContent = post.textContent.toLowerCase();
  153. shouldHide = keywordPattern.test(postContent);
  154. }
  155.  
  156. if (shouldHide) {
  157. post.classList.add('content-filtered');
  158. const parentArticle = post.closest(postSelector);
  159. if (parentArticle) {
  160. parentArticle.classList.add('content-filtered');
  161. }
  162. filteredCount++;
  163. pendingUpdates++;
  164. batchUpdateCounter();
  165. }
  166. }
  167.  
  168. const debouncedUpdate = debounce((posts) => {
  169. processPostsBatch(Array.from(posts));
  170. }, 100);
  171.  
  172. function debounce(func, wait) {
  173. let timeout;
  174. return (...args) => {
  175. clearTimeout(timeout);
  176. timeout = setTimeout(() => {
  177. timeout = null;
  178. func.apply(this, args);
  179. }, wait);
  180. };
  181. }
  182.  
  183. async function init() {
  184. blocklistArray = (await GM.getValue('blocklist', [])).map(item => item.toLowerCase());
  185. keywordPattern = getKeywordPattern(blocklistArray);
  186. batchUpdateCounter();
  187.  
  188. const observerTarget = document.querySelector('.main-content') || document.body;
  189. const observer = new MutationObserver(mutations => {
  190. const newPosts = new Set();
  191. mutations.forEach(mutation => {
  192. mutation.addedNodes.forEach(node => {
  193. if (node.nodeType === Node.ELEMENT_NODE) {
  194. if (node.matches?.(postSelector)) {
  195. newPosts.add(node);
  196. }
  197. node.querySelectorAll?.(postSelector).forEach(post => newPosts.add(post));
  198. }
  199. });
  200. });
  201. if (newPosts.size > 0) {
  202. debouncedUpdate(newPosts);
  203. }
  204. });
  205.  
  206. observer.observe(observerTarget, { childList: true, subtree: true });
  207.  
  208. const initialPosts = document.querySelectorAll(postSelector);
  209. if (initialPosts.length > 0) {
  210. debouncedUpdate(initialPosts);
  211. }
  212. }
  213.  
  214. await init();
  215. })();