Auto Copy Selected Text (with deduplication & trim)

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

您需要先安装一个扩展,例如 篡改猴Greasemonkey暴力猴,之后才能安装此脚本。

您需要先安装一个扩展,例如 篡改猴暴力猴,之后才能安装此脚本。

您需要先安装一个扩展,例如 篡改猴暴力猴,之后才能安装此脚本。

您需要先安装一个扩展,例如 篡改猴Userscripts ,之后才能安装此脚本。

您需要先安装一款用户脚本管理器扩展,例如 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);
    }
  });
})();