Reddit NSFW Filter

A userscript to show only NSFW entries on the Reddit search page

  1. // ==UserScript==
  2. // @name Reddit NSFW Filter
  3. // @namespace Reddit-NSFW-Filter
  4. // @version 1.0
  5. // @description A userscript to show only NSFW entries on the Reddit search page
  6. // @author Mortality577
  7. // @license MIT
  8. // @match *://*.reddit.com/search/*
  9. // @grant none
  10. // ==/UserScript==
  11.  
  12. (() => {
  13. 'use strict';
  14.  
  15. // Array of selectors to identify NSFW content
  16. const nsfwSelectors = [
  17. '.text-category-nsfw', // Text tag for NSFW
  18. 'svg[icon-name="nsfw-fill"]', // SVG icon for NSFW
  19. '[data-faceplate-tracking-context*="\"nsfw\":true"]' // JSON data indicating NSFW
  20. ];
  21.  
  22. // Function to check if an element or its children contains an NSFW tag
  23. const containsNSFWTag = (element) =>
  24. nsfwSelectors.some(selector => {
  25. try {
  26. return element.querySelector(selector);
  27. } catch (e) {
  28. console.error(`Error querying selector ${selector}:`, e);
  29. return false; // If an error occurs, assume the selector isn't valid
  30. }
  31. });
  32.  
  33. // Function to filter NSFW entries
  34. const filterNSFW = () => {
  35. document
  36. .querySelectorAll('faceplate-tracker[data-testid="search-community"]')
  37. .forEach(entry => {
  38. entry.style.display = containsNSFWTag(entry) ? '' : 'none'; // Show only NSFW
  39. });
  40. };
  41.  
  42. // Utility function for debouncing the filter function
  43. const debounce = (func, wait) => {
  44. let timeout;
  45. return (...args) => {
  46. clearTimeout(timeout);
  47. timeout = setTimeout(() => func.apply(this, args), wait);
  48. };
  49. };
  50.  
  51. // Initial filtering on page load
  52. filterNSFW();
  53.  
  54. // Mutation observer to run the filter function when new content is added
  55. const observer = new MutationObserver(debounce(filterNSFW, 300)); // Debounce to avoid excessive calls
  56. observer.observe(document.body, { childList: true, subtree: true }); // Watch for changes in the entire document
  57. })();