從舊到新:複製功能演進
| 時代 | 方法 | 限制 |
| IE 專屬 | window.clipboardData.setData() | 僅 IE 支援,需使用者授權彈窗 |
| 傳統 Hack | document.execCommand('copy') + 隱藏 textarea | 已棄用、同步阻塞、需使用者互動觸發 |
| 現代標準 | Clipboard API (navigator.clipboard.writeText()) | 非同步、Promise、需 HTTPS/localhost、需權限 |
現代標準實作(推薦)
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>複製到剪貼板 - 現代實作</title>
<style>
.copy-box { display: flex; gap: 8px; align-items: center; margin: 1rem 0; flex-wrap: wrap; }
.copy-input { flex: 1; min-width: 200px; padding: 8px 12px; border: 1px solid #ddd; border-radius: 4px; font-family: monospace; }
.copy-btn { padding: 8px 16px; background: #0066cc; color: #fff; border: none; border-radius: 4px; cursor: pointer; font-size: 14px; transition: background 0.2s; }
.copy-btn:hover { background: #0052a3; }
.copy-btn:disabled { background: #ccc; cursor: not-allowed; }
.copy-btn.copied { background: #28a745; }
.toast { position: fixed; bottom: 20px; right: 20px; padding: 12px 20px; background: #333; color: #fff; border-radius: 4px; opacity: 0; transform: translateY(20px); transition: all 0.3s; z-index: 9999; }
.toast.show { opacity: 1; transform: translateY(0); }
</style>
</head>
<body>
<h2>基本複製功能</h2>
<div class="copy-box">
<input type="text" class="copy-input" id="text1" value="https://example.com/api/token/abc123" readonly>
<button class="copy-btn" data-target="text1">複製</button>
</div>
<h2>動態生成內容複製</h2>
<div class="copy-box">
<input type="text" class="copy-input" id="text2" placeholder="輸入內容後點擊複製">
<button class="copy-btn" data-target="text2">複製輸入內容</button>
</div>
<h2>複製指定文字(非輸入框)</h2>
<button class="copy-btn" id="copyFixed">複製固定文字:Hello HTML5!</button>
<div class="toast" id="toast">已複製到剪貼板</div>
<script>
const toast = document.getElementById('toast');
function showToast(msg = '已複製到剪貼板') {
toast.textContent = msg;
toast.classList.add('show');
setTimeout(() => toast.classList.remove('show'), 2000);
}
async function copyToClipboard(text, btn) {
try {
await navigator.clipboard.writeText(text);
showToast();
if (btn) {
btn.classList.add('copied');
btn.textContent = '已複製!';
setTimeout(() => {
btn.classList.remove('copied');
btn.textContent = '複製';
}, 2000);
}
return true;
} catch (err) {
console.error('複製失敗:', err);
showToast('複製失敗:' + err.message);
return false;
}
}
// 綁定輸入框複製按鈕
document.querySelectorAll('.copy-btn[data-target]').forEach(btn => {
btn.addEventListener('click', () => {
const input = document.getElementById(btn.dataset.target);
copyToClipboard(input.value, btn);
});
});
// 固定文字複製
document.getElementById('copyFixed').addEventListener('click', () => {
copyToClipboard('Hello HTML5! 這是使用 Clipboard API 複製的固定文字。',
document.getElementById('copyFixed'));
});
// 鍵盤快捷鍵支援:Ctrl/Cmd + Shift + C 複製第一個輸入框
document.addEventListener('keydown', e => {
if ((e.ctrlKey || e.metaKey) && e.shiftKey && e.key === 'C') {
e.preventDefault();
copyToClipboard(document.getElementById('text1').value);
}
});
</script>
</body>
</html>
Clipboard API 核心方法
| 方法 | 說明 | 回傳 |
navigator.clipboard.writeText(text) | 寫入純文字 | Promise<void> |
navigator.clipboard.readText() | 讀取純文字 | Promise<string> |
navigator.clipboard.write(data) | 寫入任意資料(圖片、HTML、檔案) | Promise<void> |
navigator.clipboard.read() | 讀取任意資料 | Promise<ClipboardItems> |
權限與安全性
- 安全上下文:必須在 HTTPS 或
localhost 下運行
- 使用者互動:需在使用者手勢(點擊、按鍵)觸發的事件中呼叫
- 權限查詢:
navigator.permissions.query({name: 'clipboard-write'})
- 權限狀態:
granted、prompt、denied
降級方案:支援舊版瀏覽器
async function copyTextFallback(text) {
// 1. 嘗試現代 API
if (navigator.clipboard && window.isSecureContext) {
return navigator.clipboard.writeText(text);
}
// 2. 降級:execCommand(已棄用但廣泛支援)
const textarea = document.createElement('textarea');
textarea.value = text;
textarea.style.position = 'fixed';
textarea.style.opacity = '0';
document.body.appendChild(textarea);
textarea.select();
try {
const successful = document.execCommand('copy');
if (!successful) throw new Error('execCommand failed');
} finally {
document.body.removeChild(textarea);
}
}
// 使用
copyTextFallback('要複製的文字').then(() => console.log('成功'));
進階:複製富文本/HTML/圖片
async function copyRichContent() {
const htmlContent = `
<h1>標題</h1>
<p>這是<strong>富文本</strong>內容</p>
<ul><li>項目 1</li><li>項目 2</li></ul>
`;
const blob = new Blob([htmlContent], { type: 'text/html' });
const data = [new ClipboardItem({ 'text/html': blob })];
await navigator.clipboard.write(data);
console.log('富文本已複製,貼上到 Word/部落格編輯器可保留格式');
}
// 複製圖片
async function copyImage(imageUrl) {
const response = await fetch(imageUrl);
const blob = await response.blob();
await navigator.clipboard.write([
new ClipboardItem({ [blob.type]: blob })
]);
}
常見問題排查
| 問題 | 原因 | 解決 |
| Promise reject: NotAllowedError | 非使用者手勢觸發、非安全上下文 | 確保在 click 事件中呼叫、使用 HTTPS |
| HTTP 下無法使用 | 安全策略限制 | 本地開發用 localhost、部署強制 HTTPS |
| Safari 不支援 read() | 瀏覽器實作進度不同 | 功能偵測後提供降級或隱藏功能 |
| 複製大量文字失敗 | 瀏覽器限制單次大小 | 分批複製或提供下載檔案替代 |