copyTextToClipboard
直接調(diào)用會(huì)出現(xiàn) DOMException: Document is not focused.
最好主動(dòng)觸發(fā)辫封,如 click
后調(diào)用
function clipboardCopy (text) {
if (navigator.clipboard) { // 如果瀏覽器兼容該 API
return navigator.clipboard.writeText(text).catch(function (err) {
throw (err !== undefined ? err : new DOMException('The request is not allowed', 'NotAllowedError'))
})
}
// 或者使用 document.execCommand()
// 把需要復(fù)制的文本放入 <span>
const span = document.createElement('span')
span.textContent = text
// 保留文本樣式
span.style.whiteSpace = 'pre'
// 把 <span> 放進(jìn)頁面
document.body.appendChild(span)
// 創(chuàng)建選擇區(qū)域
const selection = window.getSelection()
const range = window.document.createRange()
selection.removeAllRanges()
range.selectNode(span)
selection.addRange(range)
// 復(fù)制文本到剪切板
let success = false
try {
success = window.document.execCommand('copy')
} catch (err) {
console.log('error', err)
}
// 清除戰(zhàn)場
selection.removeAllRanges()
window.document.body.removeChild(span)
return success
? Promise.resolve()
: Promise.reject(new DOMException('The request is not allowed', 'NotAllowedError'))
}