Smart Copy Image

Custom "Copy Image As" with better filename

您需要先安装一款用户脚本管理器扩展,例如 Tampermonkey 篡改猴Greasemonkey 油猴子Violentmonkey 暴力猴,才能安装此脚本。

您需要先安装一款用户脚本管理器扩展,例如 Tampermonkey 篡改猴,才能安装此脚本。

您需要先安装一款用户脚本管理器扩展,例如 Tampermonkey 篡改猴Violentmonkey 暴力猴,才能安装此脚本。

您需要先安装一款用户脚本管理器扩展,例如 Tampermonkey 篡改猴Userscripts ,才能安装此脚本。

您需要先安装一款用户脚本管理器扩展,例如 Tampermonkey 篡改猴,才能安装此脚本。

您需要先安装一款用户脚本管理器扩展后才能安装此脚本。

(我已经安装了用户脚本管理器,让我安装!)

您需要先安装一款用户样式管理器扩展,比如 Stylus,才能安装此样式。

您需要先安装一款用户样式管理器扩展,比如 Stylus,才能安装此样式。

您需要先安装一款用户样式管理器扩展,比如 Stylus,才能安装此样式。

您需要先安装一款用户样式管理器扩展后才能安装此样式。

您需要先安装一款用户样式管理器扩展后才能安装此样式。

您需要先安装一款用户样式管理器扩展后才能安装此样式。

(我已经安装了用户样式管理器,让我安装!)

// ==UserScript==
// @name         Smart Copy Image
// @namespace    http://tampermonkey.net/
// @version      1.0
// @description  Custom "Copy Image As" with better filename
// @match        *://*/*
// @grant        GM_setClipboard
// ==/UserScript==

(function () {
    'use strict';

    let menu;

    document.addEventListener('contextmenu', async (e) => {
        const img = e.target.closest('img');
        if (!img) return;

        e.preventDefault();

        if (menu) menu.remove();

        menu = document.createElement('div');
        menu.style.position = 'fixed';
        menu.style.top = `${e.clientY}px`;
        menu.style.left = `${e.clientX}px`;
        menu.style.background = '#222';
        menu.style.color = '#fff';
        menu.style.padding = '8px';
        menu.style.borderRadius = '6px';
        menu.style.zIndex = 999999;
        menu.style.cursor = 'pointer';
        menu.textContent = 'Copy image as smart name';

        menu.onclick = async () => {
            try {
                const response = await fetch(img.src);
                const blob = await response.blob();

                // Generate better filename
                let name = img.alt || img.src.split('/').pop().split('?')[0];
                name = name || 'image';

                // Clean filename
                name = name.replace(/[^\w.-]+/g, '_');

                // Clipboard API
                await navigator.clipboard.write([
                    new ClipboardItem({ [blob.type]: blob })
                ]);

                console.log(`Copied as: ${name}`);
            } catch (err) {
                console.error(err);
            }

            menu.remove();
        };

        document.body.appendChild(menu);
    });

    document.addEventListener('click', () => {
        if (menu) menu.remove();
    });
})();