Copy Url

Copy current page url as text & link

  1. // ==UserScript==
  2. // @name Copy Url
  3. // @namespace http://tampermonkey.net/
  4. // @version 1.0
  5. // @license GPL-3.0-only
  6. // @description Copy current page url as text & link
  7. // @author Kingron
  8. // @match *://*/*
  9. // @icon data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==
  10. // @grant GM_registerMenuCommand
  11. // @grant GM_openInTab
  12. // ==/UserScript==
  13.  
  14. (function() {
  15. 'use strict';
  16. var linkMenu;
  17. var linkMove;
  18.  
  19. function copy(title, url, event) {
  20. const href = `<a href="${url}" title="${decodeURIComponent(url)}">${title.trim()}</a>`;
  21.  
  22. try {
  23. const clipboardItem = new ClipboardItem({
  24. 'text/plain': new Blob([url], { type: 'text/plain' }),
  25. 'text/html': new Blob([href], { type: 'text/html' })
  26. });
  27. navigator.clipboard.write([clipboardItem]);
  28. console.log('复制成功:', title, href);
  29. } catch (err) {
  30. console.error("复制失败: ", err);
  31. const cd = event?.clipboardData || window.clipboardData;
  32. if (cd) {
  33. console.log('使用老方法复制: ', title, href);
  34. cd.setData('text/plain', url);
  35. cd.setData('text/html', href);
  36. }
  37. }
  38. }
  39.  
  40. document.addEventListener('mousemove', function(event) {
  41. linkMove = event.target.closest('a');
  42. });
  43.  
  44. document.addEventListener('copy', async function (event) {
  45. const selection = document.getSelection();
  46. if (selection && selection.toString().trim()) {
  47. return; // If selection then return
  48. }
  49. if (linkMove) {
  50. copy(linkMove.textContent, linkMove.href, event);
  51. } else {
  52. copy(document.title, window.location.href, event);
  53. }
  54.  
  55. event.preventDefault();
  56. });
  57.  
  58. GM_registerMenuCommand('复制超链接', function(e) {
  59. if (linkMenu) copy(linkMenu.textContent || linkMenu.innerText || linkMenu.href, linkMenu.href || window.getSelection().toString());
  60. });
  61. GM_registerMenuCommand('复制链接文字', function(e) {
  62. if (linkMenu) navigator.clipboard.writeText(linkMenu.textContent || linkMenu.innerText || window.getSelection().toString() || linkMenu.href);
  63. });
  64. GM_registerMenuCommand('复制解码后的链接地址', function(e) {
  65. if (linkMenu) navigator.clipboard.writeText(decodeURIComponent(linkMenu.href));
  66. });
  67.  
  68. document.addEventListener('contextmenu', function(event) {
  69. linkMenu = event.target.closest('a');
  70. });
  71. })();