async function copyToClipboard(text) {
try {
await navigator.clipboard.writeText(text);
return { success: true };
} catch (err) {
console.warn('Clipboard API 失效,嘗試降級:', err);
return fallbackCopy(text);
}
}
// 支持檢測
if (navigator.clipboard && window.isSecureContext) {
// HTTPS 或 localhost 可用
}
優勢:異步、權限模型、無 Flash、支持圖片/文件等豐富數據類型。
function execCommandCopy(text) {
const textarea = document.createElement('textarea');
textarea.value = text;
textarea.style.position = 'fixed';
textarea.style.opacity = '0';
textarea.style.left = '-9999px';
document.body.appendChild(textarea);
textarea.select();
try {
const successful = document.execCommand('copy');
document.body.removeChild(textarea);
return successful;
} catch (err) {
document.body.removeChild(textarea);
return false;
}
}
注意:execCommand 已棄用,但仍被所有主流瀏覽器支持(含 IE10+)。需在用戶交互事件(click/keydown)中調用,否則會被拒絕。
// 僅作歷史參考,現代項目不建議使用
function flashCopy(text) {
var flashId = 'flashCopier';
var div = document.getElementById(flashId) || document.createElement('div');
div.id = flashId;
div.innerHTML = '
const Clipboard = {
async copy(text, options = {}) {
const { fallbackOrder = ['api', 'execCommand'], onSuccess, onError } = options;
for (const method of fallbackOrder) {
try {
let ok = false;
if (method === 'api') {
if (navigator.clipboard && window.isSecureContext) {
await navigator.clipboard.writeText(text);
ok = true;
}
} else if (method === 'execCommand') {
ok = execCommandCopy(text);
}
if (ok) { onSuccess?.(); return { success: true, method }; }
} catch (e) { /* try next */ }
}
onError?.(new Error('所有復制方案均失效'));
return { success: false };
}
};
// 使用
$('#copyBtn').click(async function() {
const text = $('#content').val();
const result = await Clipboard.copy(text, {
onSuccess: () => showToast('復制成功'),
onError: () => showToast('復制失敗,請手動 Ctrl+C')
});
});
async function copyRich(html, plainText) {
try {
const blob = new Blob([html], { type: 'text/html' });
const data = [new ClipboardItem({ 'text/html': blob, 'text/plain': new Blob([plainText], { type: 'text/plain' }) })];
await navigator.clipboard.write(data);
return true;
} catch (e) {
// 降級:只復制純文本
return await Clipboard.copy(plainText);
}
}
現代項目**首選 Clipboard API + execCommand 降級**,封裝統一 Clipboard.copy() 方法。完全放棄 Flash 方案。核心原則:用戶交互觸發、安全上下文、優雅降級、統一錯誤處理。