Auto Copy Selected Text

Automatically copy selected text to clipboard and keep the selection

目前為 2024-09-22 提交的版本,檢視 最新版本

  1. // ==UserScript==
  2. // @name Auto Copy Selected Text
  3. // @namespace http://tampermonkey.net/
  4. // @version 1.5
  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("Text copied to clipboard:", selectedText);
  28. })
  29. .catch((err) => {
  30. console.error("Failed to copy text to clipboard", err);
  31. });
  32. } else {
  33. const tempElement = document.createElement("textarea");
  34. tempElement.value = selectedText;
  35. document.body.appendChild(tempElement);
  36. tempElement.select();
  37. try {
  38. document.execCommand("copy");
  39. console.log("Text copied to clipboard:", selectedText);
  40. } catch (err) {
  41. console.error("Failed to copy text to clipboard", err);
  42. }
  43. document.body.removeChild(tempElement);
  44. }
  45. selection.removeAllRanges();
  46. selection.addRange(range);
  47. }
  48. });
  49. })();