浏览器js复制文本到剪贴板
js
export async function copyText(text) {
try {
// 优先使用 Clipboard API(HTTPS/localhost 环境)
if (navigator.clipboard && window.isSecureContext) {
await navigator.clipboard.writeText(text);
} else {
// 回退方案:使用 document.execCommand(兼容 HTTP 内网环境)
fallbackCopyTextToClipboard(text);
}
console.log('复制成功')
} catch (err) {
console.error('复制失败:', err);
}
}
// 回退方案:兼容 HTTP 内网环境
function fallbackCopyTextToClipboard(text) {
try {
const textArea = document.createElement("textarea");
textArea.value = text;
textArea.style.position = "fixed"; // 避免影响页面布局
textArea.style.top = "0";
textArea.style.left = "0";
textArea.style.width = "2em";
textArea.style.height = "2em";
textArea.style.padding = "0";
textArea.style.border = "none";
textArea.style.outline = "none";
textArea.style.boxShadow = "none";
textArea.style.background = "transparent";
document.body.appendChild(textArea);
textArea.focus();
textArea.select();
document.execCommand('copy');
} catch (err) {
console.error('复制失败(回退方案):', err);
throw err
} finally {
document.body.removeChild(textArea);
}
}