Copy URL with Hash

Add a contextmenu command to copy URL with '#' anchor

  1. // ==UserScript==
  2. // @name Copy URL with Hash
  3. // @version 0.1.1
  4. // @description Add a contextmenu command to copy URL with '#' anchor
  5. // @license MIT
  6. // @author eight04 <eight04@gmail.com>
  7. // @homepageURL https://github.com/eight04/copy-url-with-hash
  8. // @supportURL https://github.com/eight04/copy-url-with-hash/issues
  9. // @incompatible chrome
  10. // @incompatible opera
  11. // @incompatible safari
  12. // @include *
  13. // @require https://greasyfork.org/scripts/33034-gm-context/code/GM_context.js?version=219427
  14. // @grant none
  15. // @namespace https://greasyfork.org/users/813
  16. // ==/UserScript==
  17.  
  18. /* global GM_context */
  19.  
  20. (function(){
  21. let hash;
  22. const item = {
  23. label: "Copy URL with #hash",
  24. onclick() {
  25. const url = new URL(location.href);
  26. url.hash = hash;
  27. const input = document.createElement("input");
  28. input.value = url.href;
  29. document.body.appendChild(input);
  30. input.select();
  31. document.execCommand("copy");
  32. input.remove();
  33. }
  34. };
  35. GM_context.add({
  36. context: ["page", "link"],
  37. items: [item],
  38. oncontext(e) {
  39. hash = findHash(e.target);
  40. if (!hash) return false;
  41. GM_context.update(item, {label: `Copy URL with #${hash}`});
  42. }
  43. });
  44. function findHash(node) {
  45. if (node.id || node.name) {
  46. return node.id || node.name;
  47. }
  48. const anchor = node.querySelector("[id], a[name]");
  49. if (anchor) {
  50. return anchor.id || anchor.name;
  51. }
  52. const head = node.closest("h1, h2, h3, h4, h5, h6");
  53. if (head) {
  54. if (head.id) {
  55. return head.id;
  56. }
  57. const anchor = head.querySelector("[id], a[name]");
  58. if (anchor) {
  59. return anchor.id || anchor.name;
  60. }
  61. }
  62. const header = head.closest("header");
  63. if (header) {
  64. if (header.id) {
  65. return header.id;
  66. }
  67. const anchor = header.querySelector("[id], a[name]");
  68. if (anchor) {
  69. return anchor.id || anchor.name;
  70. }
  71. }
  72. }
  73. })();