Reddit Image Downloader

Adds download button for image post in reddit

  1. // ==UserScript==
  2. // @name Reddit Image Downloader
  3. // @namespace http://tampermonkey.net/
  4. // @version 2024-09-12
  5. // @description Adds download button for image post in reddit
  6. // @author FlinCode
  7. // @match https://www.reddit.com/r/*/comments/*
  8. // @icon https://www.google.com/s2/favicons?sz=64&domain=reddit.com
  9. // @grant none
  10. // @license MIT
  11. // ==/UserScript==
  12.  
  13. (function() {
  14. 'use strict';
  15.  
  16. const img = document.getElementById("post-image")
  17. if (img) {
  18. const items = img.srcset.split(",").map(item => item.trim())
  19. const imgSrc = items[items.length - 1]
  20. console.log(imgSrc)
  21. addUrls([imgSrc])
  22. } else {
  23. const imgs = document.getElementsByClassName("media-lightbox-img")
  24.  
  25. let urls = []
  26. for (let i = 0; i < imgs.length; i++) {
  27. const img = imgs[i]
  28. const items = img.srcset.split(",").map(item => item.trim())
  29. const imgSrc = items[items.length - 1]
  30. urls.push(imgSrc)
  31. console.log("Image: " + i, imgSrc)
  32. }
  33. addUrls(urls)
  34. }
  35.  
  36. function addUrls(urls) {
  37. const box = querySelectorAllShadows("shreddit-post")[0]
  38. // add url buttons to download
  39. urls.forEach((url, idx) => {
  40. url = convertUrl(url)
  41. const a = document.createElement("a")
  42. a.innerHTML = "Download " + (idx + 1)
  43. a.href = url
  44. a.download = url.split("/").pop()
  45. a.target = "_blank"
  46. a.className = "button-bordered button-small button join-btn leading-none min-w-[100px]"
  47. a.style.padding = "9px";
  48. a.style.textDecoration = "none"
  49. a.style.marginLeft = "5px"
  50. box.appendChild(a)
  51. });
  52. }
  53.  
  54. // https://i.redd.it/file-name.jpeg
  55.  
  56. function convertUrl(url) {
  57. let base = "https://i.redd.it/";
  58. const u = new URL(url)
  59. const stem = u.pathname.split("v0-").pop()
  60. return base + stem
  61. }
  62.  
  63. function querySelectorAllShadows(selector, el = document.body) {
  64. const childShadows = Array.from(el.querySelectorAll('*')).
  65. map(el => el.shadowRoot).filter(Boolean);
  66.  
  67. const childResults = childShadows.map(child => querySelectorAllShadows(selector, child));
  68.  
  69. const result = Array.from(el.querySelectorAll(selector));
  70. return result.concat(childResults).flat();
  71. }
  72. })();