原文使用 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 ? '剪切成功' : '剪切失敗');
});
| 特性 | Clipboard API | execCommand |
|---|---|---|
| 支持環境 | HTTPS + 用戶交互 | HTTP/HTTPS,廣泛但棄用中 |
| 異步 | Promise | 同步 |
| 權限模型 | Permissions API 可查詢 | 無 |
| 支持數據類型 | 文本、HTML、圖片、文件 | 僅文本 |
| 剪切支持 | 無直接 API | 支持 (需可編輯上下文) |
| 未來 | 標準演進方向 | 將被移除 |
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)處理邊緣情況。