View Full Twitter Image

Undo Twitter's insistence to down-res images when viewing on its dedicated page and add a button to download the full image without the weird file extensions which don't count as actual images.

Version au 02/09/2019. Voir la dernière version.

  1. // ==UserScript==
  2. // @name View Full Twitter Image
  3. // @version 2.0.1
  4. // @description Undo Twitter's insistence to down-res images when viewing on its dedicated page and add a button to download the full image without the weird file extensions which don't count as actual images.
  5. // @author ForgottenUmbrella
  6. // @match https://pbs.twimg.com/media/*
  7. // @grant none
  8. // @noframes
  9. // @namespace https://greasyfork.org/users/83187
  10. // ==/UserScript==
  11.  
  12. "use strict";
  13.  
  14. // Returns the URL to the original image file (as a string), given a `location` object.
  15. function ogImageUrl(location) {
  16. let url = new URL(location.href);
  17. const isNewFormat = url.search.length > 0;
  18. if (isNewFormat) {
  19. // The old URL format is https://pbs.twimg/media/hash.jpg:orig.
  20. // The new URL format is https://pbs.twimg.com/media/hash?format=jpg&name=orig.
  21. let params = new URLSearchParams(url.search);
  22. params.set("name", "orig");
  23. url.search = params.toString();
  24. return url.href;
  25. }
  26. return url.href.replace(":large", "") + ":orig";
  27. }
  28.  
  29. // Returns the filename of the original image, given a `location` to said image.
  30. function imageName(location) {
  31. const filename = location.pathname.split("/").pop();
  32. // Remove the ":orig" tag if Twitter is using the old URL format.
  33. return filename.replace(":orig", "");
  34. }
  35.  
  36. // Saves the webpage/file being viewed as `filename`.
  37. function download(filename) {
  38. let element = document.createElement("a");
  39. // The `download` attribute only works if `href` is set.
  40. element.href = location.href;
  41. element.download = filename;
  42. element.style.display = "none";
  43. document.body.appendChild(element);
  44. element.click();
  45. document.body.removeChild(element);
  46. }
  47.  
  48. // View original image file.
  49. const isOgImage = location.href.includes("orig");
  50. if (!isOgImage) {
  51. location.assign(ogImageUrl(location));
  52. }
  53. // Add spacing between image and download button.
  54. const image = document.getElementsByTagName("img")[0];
  55. const spacing = document.createElement("p");
  56. document.body.insertBefore(spacing, image);
  57. // Add download button.
  58. let button = document.createElement("button");
  59. button.innerHTML = "Download";
  60. button.onclick = () => void download(imageName(location));
  61. document.body.insertBefore(button, spacing);