Copy URL with Hash

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

目前为 2017-09-21 提交的版本。查看 最新版本

  1. // ==UserScript==
  2. // @name Copy URL with Hash
  3. // @version 0.1.0
  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"],
  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. const anchor = head.querySelector("[id], a[name]");
  55. if (anchor) {
  56. return anchor.id || anchor.name;
  57. }
  58. }
  59. }
  60. })();