最推荐方式是 navigator.clipboard.writeText(),现代浏览器均支持,需 HTTPS 或 localhost 安全上下文,必须用户触发;旧浏览器降级用 document.execCommand("copy")。
用 JavaScript 实现复制到剪贴板,最推荐、最可靠的方式是使用原生的 navigator.clipboard.writeText() API。它现代、安全、无需依赖第三方库,且支持异步操作和错误处理。
这是目前主流浏览器(Chrome 66+、Firefox 63+、Edge 79+、Safari 13.1+)都支持的标准 API,需在安全上下文(HTTPS 或 localhost)中运行。
navigator.clipboard.writeText("要复制的文本")
async/await 使用,便于处理成功或失败示例:
async function copyToClipboard(text) {
try {
await navigator.clipboard.writeText(text);
console.log("复制成功");
} catch (err) {
console.error("复制失败:", err);
}
}
// 绑定到按钮点击
document.getElementById("copyBtn").addEventListener("click", () => {
copyToClipboard("Hello, world!");
});
适用于 IE11、旧版 Safari 等不支持 navigator.clipboard 的环境,但已被废弃(Deprecated),仅作降级方案。
或 元素,把内容填入并选中document.execCommand("copy")
示例(带兼容逻辑):
function fallbackCopy(text) {
const textarea = document.createElement("textarea");
textarea.value = text;
textarea.style.position = "fixed"; // 避免滚动和显示
document.body.appendChild(textarea);
textarea.select();
try {
document.execCommand("copy");
console.log("已通过 execCommand 复制");
} catch (err) {
console.error("execCommand 复制失败", err);
} finally {
document.body.removeChild(textarea);
}
}
实际项目中建议封装一个健壮的复制函数,自动判断环境并选择最优方式。
先检测 navigator.clipboard?.writeText 是否可用execCommand 方案这样既能用上新 API 的便利性,又不影响老用户。
复制功能看似简单,但容易踩坑:
navigator.clipboard.write()(更复杂,需构造 ClipboardItem)基本上就这些。用好 navigator.clipboard.writeText(),再加一层降级兜底,就能覆盖绝大多数场景了。