GitHub HTML Preview

A userscript that adds preview links to HTML files

  1. // ==UserScript==
  2. // @name GitHub HTML Preview
  3. // @version 1.0.6
  4. // @description A userscript that adds preview links to HTML files
  5. // @license MIT
  6. // @author Rob Garrison
  7. // @namespace https://github.com/Mottie
  8. // @match https://github.com/*
  9. // @run-at document-idle
  10. // @grant none
  11. // @require https://greasyfork.org/scripts/28721-mutations/code/mutations.js?version=1108163
  12. // @require https://greasyfork.org/scripts/398877-utils-js/code/utilsjs.js?version=1079637
  13. // @icon https://github.githubassets.com/pinned-octocat.svg
  14. // @supportURL https://github.com/Mottie/GitHub-userscripts/issues
  15. // ==/UserScript==
  16.  
  17. /* global $ $$ on */
  18. (() => {
  19. "use strict";
  20. // Example page: https://github.com/codrops/DecorativeLetterAnimations
  21. // Source: https://github.com/htmlpreview/htmlpreview.github.com
  22. const prefix = "https://htmlpreview.github.io/?";
  23. // html & htm extensions
  24. const regex = /\.html?$/;
  25.  
  26. const link = document.createElement("a");
  27. link.className = "ghhp-btn py-0 v-align-baseline tooltipped tooltipped-e";
  28. link.setAttribute("aria-label", "Open in new tab");
  29. link.target = "_blank";
  30. link.innerHTML = `
  31. <svg class="octicon v-align-text-bottom" xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="currentColor">
  32. <path d="M19 19H5V5h7V3H5a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7h-2v7zM14 3v2h3.59l-9.83 9.83 1.41 1.41L19 6.41V10h2V3h-7z"/>
  33. </svg>`;
  34. link.style.marginRight = ".25rem";
  35.  
  36. function addLink(el) {
  37. const cell = el.closest(".js-navigation-item div[role='rowheader'] span");
  38. if (cell && !$(".ghhp-btn", cell)) {
  39. const preview = link.cloneNode(true);
  40. preview.href = prefix + el.href;
  41. cell.prepend(preview);
  42. }
  43. }
  44.  
  45. function init() {
  46. if ($("#files")) {
  47. const files = $("#files").parentElement;
  48. $$(".js-navigation-item div[role='rowheader'] .js-navigation-open", files).forEach(el => {
  49. if (regex.test(el.title)) {
  50. addLink(el);
  51. }
  52. });
  53. }
  54. }
  55.  
  56. on(document, "ghmo:container", () => {
  57. // init after a short delay to allow rendering of file list
  58. setTimeout(() => {
  59. init();
  60. }, 200);
  61. });
  62. init();
  63.  
  64. })();