Auto Copy Selected Text (with deduplication & trim)

Automatically copy selected text to clipboard if it's new and meaningful

  1. // ==UserScript==
  2. // @name Auto Copy Selected Text (with deduplication & trim)
  3. // @namespace http://tampermonkey.net/
  4. // @version 1.7
  5. // @description Automatically copy selected text to clipboard if it's new and meaningful
  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. let lastCopiedText = "";
  17.  
  18. document.addEventListener("mouseup", () => {
  19. const selection = window.getSelection();
  20. const selectedText = selection.toString().trim(); // 去掉前后空白
  21.  
  22. // 跳过空白内容或与上次相同内容
  23. if (!selectedText || selectedText === lastCopiedText) return;
  24.  
  25. lastCopiedText = selectedText;
  26.  
  27. const range = selection.getRangeAt(0);
  28. if (navigator.clipboard) {
  29. navigator.clipboard
  30. .writeText(selectedText)
  31. .then(() => {
  32. console.log("Copied:", selectedText);
  33. })
  34. .catch((err) => {
  35. console.error("Failed to copy", err);
  36. });
  37. } else {
  38. const tempElement = document.createElement("textarea");
  39. tempElement.value = selectedText;
  40. document.body.appendChild(tempElement);
  41. tempElement.select();
  42. try {
  43. document.execCommand("copy");
  44. console.log("Copied (fallback):", selectedText);
  45. selection.removeAllRanges();
  46. selection.addRange(range);
  47. } catch (err) {
  48. console.error("Fallback copy failed", err);
  49. }
  50. document.body.removeChild(tempElement);
  51. }
  52. });
  53. })();