Auto Copy Selected Text

Automatically copy selected text to clipboard and keep the selection

目前為 2024-11-12 提交的版本,檢視 最新版本

  1. // ==UserScript==
  2. // @name Auto Copy Selected Text
  3. // @namespace http://tampermonkey.net/
  4. // @version 1.6
  5. // @description Automatically copy selected text to clipboard and keep the selection
  6. // @author liuweiqing
  7. // @match *://*/*
  8. // @grant none
  9. // @license MIT
  10. // @icon https://icons.iconarchive.com/icons/gartoon-team/gartoon-places/256/user-desktop-icon.png
  11. // ==/UserScript==
  12.  
  13. (function () {
  14. ("use strict");
  15.  
  16. // 监听鼠标松开的事件
  17. document.addEventListener("mouseup", () => {
  18. const selection = window.getSelection();
  19. const selectedText = selection.toString();
  20.  
  21. if (selectedText) {
  22. const range = selection.getRangeAt(0);
  23. if (navigator.clipboard) {
  24. navigator.clipboard
  25. .writeText(selectedText)
  26. .then(() => {
  27. console.log(
  28. "Text copied to clipboard in navigator clipboard:",
  29. selectedText
  30. );
  31. })
  32. .catch((err) => {
  33. console.error("Failed to copy text to clipboard", err);
  34. });
  35. } else {
  36. const tempElement = document.createElement("textarea");
  37. tempElement.value = selectedText;
  38. document.body.appendChild(tempElement);
  39. tempElement.select();
  40. try {
  41. document.execCommand("copy");
  42. console.log("Text copied to clipboard in execCommand:", selectedText);
  43. selection.addRange(range);
  44. } catch (err) {
  45. console.error("Failed to copy text to clipboard", err);
  46. }
  47. document.body.removeChild(tempElement);
  48. }
  49. }
  50. });
  51. })();