navigator.clipboard.writeText 可用作复制功能,使用方法如下
navigator.clipboard.writeText('复制的内容')
该方法对部分浏览器不支持
浏览器兼容

image.png
同时,该方法也不支持非https安全模式
例如开发时容易遇见的问题,本地调试时,使用该方法可以正在使用,但部署到非安全域http环境中,此时会复制失败,控制台打印navigator.clipboard也会提示undefined。
此时我们需要应对这种情况做兼容处理:
function copyToClipboard(textToCopy) {
// navigator clipboard 需要在htts安全域中
if (navigator.clipboard && window.isSecureContext) {
return navigator.clipboard.writeText(textToCopy)
} else {
// http模式下或部分浏览器,不支持navigator.clipboard
// 创建text area
let textArea = document.createElement('textarea')
textArea.value = textToCopy
// 使text area不在viewport,同时设置不可见
textArea.style.position = 'absolute'
textArea.style.opacity = 0
textArea.style.left = '-999999px'
textArea.style.top = '-999999px'
document.body.appendChild(textArea)
textArea.focus()
textArea.select()
return new Promise((res, rej) => {
// 执行复制命令并移除文本框
document.execCommand('copy') ? res() : rej()
textArea.remove()
})
}
},