注意:该函数需要有页面事件(如点击事件)触发调用才能生效,不能直接在控制台调用
// 拷贝到剪切板
function copyToClipboard(text) {
return new Promise((resolve, reject) => {
// 确保通过用户点击触发
if (navigator.clipboard) {
// 检查当前文档是否已经聚焦,避免 DOMException 错误
if (document.hasFocus()) {
navigator.clipboard.writeText(text).then(function() {
resolve(true)
}).catch(reject);
} else {
reject('文档未聚焦,无法复制')
}
} else {
// 如果 Clipboard API 不可用,使用 document.execCommand 作为备选方案
const textArea = document.createElement('textarea');
textArea.style.position = 'fixed'; // 不占据页面空间
textArea.style.opacity = '0';
textArea.value = text;
document.body.appendChild(textArea);
textArea.select(); // 选中要复制的文本
try {
const successful = document.execCommand('copy');
if (successful) {
resolve(true)
} else {
reject('');
}
} catch (err) {
reject(err)
} finally {
document.body.removeChild(textArea); // 清理临时创建的 textarea 元素
}
}
})
}