GreasyFork Copy Code Snippet

A userscript that adds a copy code button to the greasyfork code page

  1. // ==UserScript==
  2. // @name GreasyFork Copy Code Snippet
  3. // @version 0.1.1
  4. // @description A userscript that adds a copy code button to the greasyfork code page
  5. // @license MIT
  6. // @author Rob Garrison
  7. // @namespace https://github.com/Mottie
  8. // @match https://greasyfork.org/*/scripts/*/code
  9. // @match https://sleazyfork.org/*/scripts/*/code
  10. // @run-at document-idle
  11. // @grant none
  12. // @icon https://www.google.com/s2/favicons?domain=greasyfork.org
  13. // @require https://greasyfork.org/scripts/398877-utils-js/code/utilsjs.js?version=895926
  14. // ==/UserScript==
  15. /* global $ */
  16. (() => {
  17. "use strict";
  18.  
  19. const copyCode = () => {
  20. const code = $(".code-container");
  21. if ("clipboard" in navigator) {
  22. return navigator.clipboard.writeText(code.innerText || "");
  23. }
  24.  
  25. const selection = getSelection();
  26. if (selection == null) {
  27. return Promise.reject(new Error());
  28. }
  29.  
  30. selection.removeAllRanges();
  31.  
  32. const range = document.createRange();
  33. range.selectNodeContents(code);
  34. selection.addRange(range);
  35.  
  36. document.execCommand("copy");
  37. selection.removeAllRanges();
  38. return Promise.resolve();
  39. };
  40.  
  41. const installArea = $("#install-area");
  42. if (installArea && !$(".copy-code-link")) {
  43. const copyLink = document.createElement("a");
  44. copyLink.href = "#";
  45. copyLink.className = "install-link copy-code-link";
  46. copyLink.style.marginLeft = "0.5rem";
  47. copyLink.innerHTML = `
  48. <svg aria-hidden="true" height="16" viewBox="0 0 14 16" width="14">
  49. <path fill="currentColor" fill-rule="evenodd" d="M2 13h4v1H2v-1zm5-6H2v1h5V7zm2 3V8l-3 3 3 3v-2h5v-2H9zM4.5 9H2v1h2.5V9zM2 12h2.5v-1H2v1zm9 1h1v2c-.02.28-.11.52-.3.7-.19.18-.42.28-.7.3H1c-.55 0-1-.45-1-1V4c0-.55.45-1 1-1h3c0-1.11.89-2 2-2 1.11 0 2 .89 2 2h3c.55 0 1 .45 1 1v5h-1V6H1v9h10v-2zM2 5h8c0-.55-.45-1-1-1H8c-.55 0-1-.45-1-1s-.45-1-1-1-1 .45-1 1-.45 1-1 1H3c-.55 0-1 .45-1 1z"></path>
  50. </svg>
  51. Copy code to clipboard`;
  52. copyLink.onclick = async event => {
  53. event.preventDefault();
  54. await copyCode();
  55. };
  56.  
  57. installArea.appendChild(copyLink);
  58. }
  59. })();
  60.