Greasy Fork

来自缓存

Greasy Fork is available in English.

万能复制插件(无data-copy限制版)

点击任意文本元素即复制其内容,更智能更兼容的复制工具,无需设置 data-copy 属性。

当前为 2025-07-10 提交的版本,查看 最新版本

// ==UserScript==
// @name         万能复制插件(无data-copy限制版)
// @namespace    http://tampermonkey.net/
// @version      1.7
// @description  点击任意文本元素即复制其内容,更智能更兼容的复制工具,无需设置 data-copy 属性。
// @author       You
// @match        *://*/*
// @grant        GM_setClipboard
// ==/UserScript==

(function () {
    'use strict';

    // 提示函数
    function showTip(text) {
        const tip = document.createElement('div');
        tip.innerText = text;
        tip.style.cssText = `
            position: fixed;
            top: 20px;
            right: 20px;
            background: #007bff;
            color: #fff;
            padding: 8px 16px;
            border-radius: 5px;
            font-size: 14px;
            z-index: 9999;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
        `;
        document.body.appendChild(tip);
        setTimeout(() => tip.remove(), 2000);
    }

    // 提取文本函数
    function getTextFromElement(el) {
        const tag = el.tagName.toLowerCase();
        if (tag === 'input' || tag === 'textarea') return el.value.trim();
        return el.innerText?.trim() || el.textContent?.trim() || '';
    }

    // 复制函数
    function copyText(text) {
        if (!text) return;
        if (navigator.clipboard) {
            navigator.clipboard.writeText(text).then(() => {
                showTip('已复制:' + text);
            }).catch(() => {
                GM_setClipboard(text);
                showTip('已复制(兼容模式):' + text);
            });
        } else {
            GM_setClipboard(text);
            showTip('已复制(GM_setClipboard):' + text);
        }
    }

    // 主监听器
    document.addEventListener('click', (e) => {
        let el = e.target;
        while (el && el !== document.body) {
            const tag = el.tagName.toLowerCase();
            if (['div', 'span', 'p', 'input', 'textarea', 'td', 'th', 'li', 'pre', 'code'].includes(tag)) {
                const text = getTextFromElement(el);
                if (text) copyText(text);
                break;
            }
            el = el.parentElement;
        }
    });
})();