Hacker News Infinite Scroll v2 June 2024

Automatically loads more stories as you scroll down on Hacker News.

  1. // ==UserScript==
  2. // @name Hacker News Infinite Scroll v2 June 2024
  3. // @namespace http://tampermonkey.net/
  4. // @version 1.2
  5. // @license MIT
  6. // @description Automatically loads more stories as you scroll down on Hacker News.
  7. // @author jeffscottward
  8. // @match https://news.ycombinator.com/*
  9. // @grant none
  10. // ==/UserScript==
  11.  
  12.  
  13. (function () {
  14. 'use strict';
  15.  
  16. console.log('load')
  17.  
  18. /**
  19. * Fetches the next page's content and appends it to the current page.
  20. */
  21. function loadMore() {
  22. // Find the "More" link on the page
  23. const moreLink = document.querySelector('.morelink');
  24. const pageLinkTableBody = document.querySelector('#hnmain > tbody > tr:nth-child(3) > td > table > tbody');
  25. const morespaceEl = document.querySelector('.morespace');
  26.  
  27. // Fetch the content of the next page
  28. fetch(moreLink.href)
  29. .then(response => response.text()) // Parse the response as text
  30. .then(data => {
  31. // Create a new DOM parser
  32. const parser = new DOMParser();
  33. // Parse the fetched HTML into a document
  34. const doc = parser.parseFromString(data, 'text/html');
  35. // More link
  36. const newMoreLinkHref = doc.querySelector('.morelink').href
  37. // Select the new stories and spacers from the fetched document
  38. const moreItems = doc.querySelectorAll(`
  39. #hnmain > tbody > tr:nth-child(3) > td > table > tbody > tr.athing:not(.morespace):not(.morespace + tr),
  40. #hnmain > tbody > tr:nth-child(3) > td > table > tbody > tr:not(.morespace):not(.morespace + tr),
  41. #hnmain > tbody > tr:nth-child(3) > td > table > tbody > tr.spacer:not(.morespace):not(.morespace + tr)
  42. `);
  43.  
  44.  
  45. // Convert NodeList to Array and filter out the morespace element
  46. moreItems.forEach(item => {
  47. pageLinkTableBody.insertBefore(item, morespaceEl);
  48. });
  49.  
  50. // Update the "More" link to the next page's "More" link
  51. moreLink.href = newMoreLinkHref;
  52. });
  53. }
  54.  
  55. /**
  56. * Event listener for infinite scroll.
  57. * Loads more content when the user scrolls to the bottom of the page.
  58. */
  59. window.addEventListener('scroll', () => {
  60. console.log('scroll')
  61. // Check if the user has scrolled to the bottom of the page
  62. if (window.innerHeight + window.scrollY >= document.body.offsetHeight - 100) {
  63. // Load more content
  64. loadMore();
  65.  
  66. }
  67. });
  68.  
  69. })();
  70.  
  71.  
  72.  
  73.