Reddit Sort Comments by old

Append ?sort=old to all /comments/ links, waiting for feed to load

  1. // ==UserScript==
  2. // @name Reddit Sort Comments by old
  3. // @version 1.3
  4. // @description Append ?sort=old to all /comments/ links, waiting for feed to load
  5. // @author Rayman30
  6. // @license MIT
  7. // @match https://www.reddit.com/*
  8. // @grant none
  9. // @run-at document-end
  10. // @namespace https://github.com/rayman1972
  11. // ==/UserScript==
  12. (function() {
  13. 'use strict';
  14.  
  15. /**
  16. * Rewrites all comment links so that, if they don't have a "sort" param,
  17. * we add "?sort=old".
  18. */
  19. function rewriteCommentLinks() {
  20. // Grab all anchor tags whose href includes "/comments/"
  21. const anchors = document.querySelectorAll('a[href*="/comments/"]');
  22.  
  23. anchors.forEach(a => {
  24. try {
  25. const url = new URL(a.href);
  26. // If no sort param, set it to "old"
  27. if (!url.searchParams.has('sort')) {
  28. url.searchParams.set('sort', 'old');
  29. a.href = url.toString();
  30. }
  31. } catch (err) {
  32. // Ignore any invalid URLs
  33. }
  34. });
  35.  
  36. console.log('[Reddit Sort=old] Rewrote comment links.');
  37. }
  38.  
  39. /**
  40. * Initialize:
  41. * 1) Wait for window load to ensure initial feed is done.
  42. * 2) Rewrites links once.
  43. * 3) Sets a MutationObserver to catch newly inserted links (infinite scroll).
  44. */
  45. function init() {
  46. // First, rewrite links once on the "window.load" event
  47. window.addEventListener('load', () => {
  48. console.log('[Reddit Sort=old] Window load event fired. Rewriting links...');
  49. rewriteCommentLinks();
  50. });
  51.  
  52. // Then keep an eye out for new content (infinite scrolling)
  53. const observer = new MutationObserver(() => {
  54. rewriteCommentLinks();
  55. });
  56. observer.observe(document.body, { childList: true, subtree: true });
  57. }
  58.  
  59. // Start
  60. init();
  61. })();