萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

JavaScript 實現複製/剪切到剪貼板:現代 API 與降級方案

原版代碼分析

原文使用 createTextRange() + execCommand('Copy'/'Cut'),這是 IE 專有 API,現代瀏覽器已棄用/移除。需遷移至標準 Clipboard API。

現代標準方案


/**
 * 統一複製/剪切函數
 * @param {string} text - 要複製的文本
 * @param {boolean} cut - 是否為剪切(僅在可編輯元素中有效)
 * @returns {Promise}
 */
async function clipboardAction(text, cut = false) {
    // 1. 現代 Clipboard API (HTTPS + 用戶交互)
    if (navigator.clipboard && window.isSecureContext) {
        try {
            if (cut) {
                // 剪切需在可編輯上下文,通常配合 document.execCommand('cut')
                // Clipboard API 無直接 cut,需選中內容後 execCommand
                return await clipboardLegacy(text, true);
            }
            await navigator.clipboard.writeText(text);
            return true;
        } catch (e) {
            console.warn('Clipboard API 失敗,降級:', e);
        }
    }
    // 2. 降級方案
    return clipboardLegacy(text, cut);
}

/**
 * 降級方案:execCommand + 隱藏 textarea
 */
function clipboardLegacy(text, cut = false) {
    return new Promise(resolve => {
        const isInput = cut && (document.activeElement.tagName === 'INPUT' || document.activeElement.tagName === 'TEXTAREA');
        let target = document.activeElement;
        
        if (!isInput) {
            // 創建臨時 textarea
            target = document.createElement('textarea');
            target.value = text;
            target.style.cssText = 'position:fixed;left:-9999px;top:0;opacity:0;';
            document.body.appendChild(target);
        }
        
        target.select();
        if (cut) target.setSelectionRange(0, target.value.length); // 確保全選
        
        let success = false;
        try {
            success = document.execCommand(cut ? 'cut' : 'copy');
        } catch (e) {}
        
        if (!isInput) document.body.removeChild(target);
        resolve(success);
    });
}

// 使用示例
document.getElementById('copyBtn').addEventListener('click', async () => {
    const ok = await clipboardAction('要複製的文本');
    showToast(ok ? '複製成功' : '複製失敗,請手動 Ctrl+C');
});

document.getElementById('cutBtn').addEventListener('click', async () => {
    const ok = await clipboardAction('', true); // 剪切當前輸入框選中內容
    showToast(ok ? '剪切成功' : '剪切失敗');
});

HTML 示例




核心差異對比

特性Clipboard APIexecCommand
支持環境HTTPS + 用戶交互HTTP/HTTPS,廣泛但棄用中
異步Promise同步
權限模型Permissions API 可查詢無
支持數據類型文本、HTML、圖片、文件僅文本
剪切支持無直接 API支持 (需可編輯上下文)
未來標準演進方向將被移除

進階:複製富文本/HTML


async function copyHtml(html, plainText) {
    if (!navigator.clipboard || !window.ClipboardItem) return false;
    try {
        const htmlBlob = new Blob([html], { type: 'text/html' });
        const textBlob = new Blob([plainText], { type: 'text/plain' });
        const item = new ClipboardItem({ 'text/html': htmlBlob, 'text/plain': textBlob });
        await navigator.clipboard.write([item]);
        return true;
    } catch (e) {
        console.error('HTML 複製失敗:', e);
        return false;
    }
}

權限檢查


async function checkClipboardPermission() {
    if (!navigator.permissions) return 'unknown';
    try {
        const perm = await navigator.permissions.query({ name: 'clipboard-write' });
        return perm.state; // 'granted' | 'denied' | 'prompt'
    } catch (e) {
        return 'unknown';
    }
}

總結

**Clipboard API 是未來標準**,但需 HTTPS 和用戶交互。**execCommand 作為降級** 兼容舊環境與剪切操作。封裝統一 clipboardAction(text, cut) 函數,業務代碼一行調用。原版 createTextRange/execCommand 僅限 IE,已不可用。現代項目應直接使用 Clipboard API,配合降級庫(如 clipboard-polyfill)處理邊緣情況。

copyright © 萬盛學電腦網 all rights reserved