Auto Copy Selected Text (with deduplication & trim)

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

您需要先安裝使用者腳本管理器擴展,如 TampermonkeyGreasemonkeyViolentmonkey 之後才能安裝該腳本。

您需要先安裝使用者腳本管理器擴充功能,如 TampermonkeyViolentmonkey 後才能安裝該腳本。

您需要先安裝使用者腳本管理器擴充功能,如 TampermonkeyViolentmonkey 後才能安裝該腳本。

您需要先安裝使用者腳本管理器擴充功能,如 TampermonkeyUserscripts 後才能安裝該腳本。

你需要先安裝一款使用者腳本管理器擴展,比如 Tampermonkey,才能安裝此腳本

您需要先安裝使用者腳本管理器擴充功能後才能安裝該腳本。

(我已經安裝了使用者腳本管理器,讓我安裝!)

你需要先安裝一款使用者樣式管理器擴展,比如 Stylus,才能安裝此樣式

你需要先安裝一款使用者樣式管理器擴展,比如 Stylus,才能安裝此樣式

你需要先安裝一款使用者樣式管理器擴展,比如 Stylus,才能安裝此樣式

你需要先安裝一款使用者樣式管理器擴展後才能安裝此樣式

你需要先安裝一款使用者樣式管理器擴展後才能安裝此樣式

你需要先安裝一款使用者樣式管理器擴展後才能安裝此樣式

(我已經安裝了使用者樣式管理器,讓我安裝!)

// ==UserScript==
// @name         Auto Copy Selected Text (with deduplication & trim)
// @namespace    http://tampermonkey.net/
// @version      1.7
// @description  Automatically copy selected text to clipboard if it's new and meaningful
// @author       liuweiqing
// @match        *://*/*
// @grant        none
// @license      MIT
// @icon         https://icons.iconarchive.com/icons/gartoon-team/gartoon-places/256/user-desktop-icon.png
// ==/UserScript==

(function () {
  "use strict";

  let lastCopiedText = "";

  document.addEventListener("mouseup", () => {
    const selection = window.getSelection();
    const selectedText = selection.toString().trim(); // 去掉前后空白

    // 跳过空白内容或与上次相同内容
    if (!selectedText || selectedText === lastCopiedText) return;

    lastCopiedText = selectedText;

    const range = selection.getRangeAt(0);
    if (navigator.clipboard) {
      navigator.clipboard
        .writeText(selectedText)
        .then(() => {
          console.log("Copied:", selectedText);
        })
        .catch((err) => {
          console.error("Failed to copy", err);
        });
    } else {
      const tempElement = document.createElement("textarea");
      tempElement.value = selectedText;
      document.body.appendChild(tempElement);
      tempElement.select();
      try {
        document.execCommand("copy");
        console.log("Copied (fallback):", selectedText);
        selection.removeAllRanges();
        selection.addRange(range);
      } catch (err) {
        console.error("Fallback copy failed", err);
      }
      document.body.removeChild(tempElement);
    }
  });
})();