推荐使用 navigator.clipboard.writeText() 实现剪贴板复制,需安全上下文和用户手势触发;不支持时降级为 document.execCommand('copy'),通过临时 textarea 操作。
JavaScript 实现复制到剪贴板,现代浏览器推荐使用 navigator.clipboard.writeText(),它简洁、安全、支持异步操作;但兼容性需注意——旧版 Safari、IE 完全不支持,部分 Android 浏览器需 HTTPS 或用户手势触发。
这是当前最推荐的方式,基于 Permissions API,需在安全上下文(HTTPS 或 localhost)中运行,且通常需由用户交互(如 click 事件)触发:
if (navigator.clipboard)
navigator.clipboard.writeText('hello') 返回 Promise.catch(err => console.error('复制失败:', err))
适用于 IE11、旧版 Safari(≤13.1)等不支持 navigator.clipboard 的环境,但已被标记为废弃(deprecated),且要求元素必须可选中、聚焦:
或 ,设值并添加到 DOMel.select() 或 el.setSelectionRange(0, el.value.length)
document.execCommand('copy')(同步,返回布尔值)不要只判断浏览器类型,应按能力检测分层处理:
navigator.clipboard.writeText(),捕获异常后降级navigator.clipboard 存在但不可用,可用 document.queryCommandSupported('copy') 辅助判断可封装一个函数统一处理:
async function copyToClipboard(text) {
if (navigator.clipboard && window.isSecureContext) {
try {
await navigator.clipboard.writeText(text);
return true;
} catch (err) {
// 降级
}
}
// fallback to execCommand
const input = document.createElement('textarea');
input.value = text;
input.style.position = 'fixed';
input.style.left = '-9999px';
document.body.appendChild(input);
input.focus();
input.select();
const success = document.execCommand('copy');
document.body.removeChild(input);
return success;
}