function handleCopyValue(text) {
//浏览器禁用了非安全域的 navigator.clipboard 对象
//在线上环境会报错 TypeError: Cannot read properties of undefined (reading 'writeText')
if (!navigator.clipboard && window.isSecureContext) {
return navigator.clipboard.writeText(text)
} else {
// 判断是否支持拷贝
if (!document.execCommand('copy')) return Promise.reject()
// 创建标签,并隐藏
const textArea = document.createElement('textarea')
textArea.style.position = 'fixed'
textArea.style.top = textArea.style.left = '-100vh'
textArea.style.opacity = '0'
textArea.value = text
document.body.appendChild(textArea)
// 聚焦、复制
textArea.focus()
textArea.select()
return new Promise((resolve, reject) => {
// 不知为何,必须写这个三目,不然copy不上
document.execCommand('copy') ? resolve() : reject()
textArea.remove()
})
}
}
handleCopyValue('复制内容')
.then(() => {
alert('复制成功')
})
.catch(() => {
alert('自动复制失败,请手动复制')
})
js复制、写入剪切板;TypeError: Cannot read properties of undefined (reading ‘writeText‘)
于 2022-11-21 17:33:14 首次发布