剪貼簿 API 歷經 document.execCommand('copy') 到現代 navigator.clipboard.writeText(),本文提供兼容 IE、Firefox、Chrome 的漸進式封裝。
async function copyModern(text) {
try {
await navigator.clipboard.writeText(text);
return true;
} catch (e) { return false; }
}
function copyLegacy(text) {
var ta = document.createElement('textarea');
ta.value = text;
ta.style.position = 'fixed';
ta.style.opacity = 0;
document.body.appendChild(ta);
ta.select();
try {
return document.execCommand('copy');
} finally {
document.body.removeChild(ta);
}
}
function copyToClipboard(text) {
if (navigator.clipboard && window.isSecureContext) {
return navigator.clipboard.writeText(text);
}
return new Promise(function(resolve) {
resolve(copyLegacy(text));
});
}
// 使用
btn.addEventListener('click', function() {
copyToClipboard('要複製的內容').then(function(ok) {
alert(ok ? '複製成功' : '複製失敗,請手動 Ctrl+C');
});
});
早期 Firefox 需 netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect'),現代版本已移除,無需處理。
execCommand 在部分瀏覽器需元素可見且可選取,故用 textarea 臨時承載。