js复制方法navigator.clipboard兼容性处理,直接执行报错 DOMException: Document is not focused
目录
兼容性处理(直接使用)
https://developer.mozilla.org/zh-CN/docs/Web/API/Navigator/clipboard
如果navigator.clipboard
不可以使用的话,使用document.execCommand
进行复制
function fnCopy(copyText) {
navigator.clipboard
.writeText(copyText)
.then(() => {
console.log('复制成功')
})
.catch(() => {
const input = document.createElement('input')
document.body.appendChild(input)
input.setAttribute('value', copyText)
input.select()
if (document.execCommand('copy')) {
document.execCommand('copy')
}
document.body.removeChild(input)
console.log('复制成功')
})
}
在控制台中执行,报错 DOMException: Document is not focused.
这种情况是浏览器的安全控制,需要用户主动触发