copyTextToClipboard

直接调用会出现 DOMException: Document is not focused.

最好主动触发,如 click 后调用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
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()

// 把需要复制的文本放入 <span>
const span = document.createElement('span')
span.textContent = text

// 保留文本样式
span.style.whiteSpace = 'pre'

// 把 <span> 放进页面
document.body.appendChild(span)

// 创建选择区域
const selection = window.getSelection()
const range = window.document.createRange()
selection.removeAllRanges()
range.selectNode(span)
selection.addRange(range)

// 复制文本到剪切板
let success = false
try {
success = window.document.execCommand('copy')
} catch (err) {
console.log('error', err)
}

// 清除战场
selection.removeAllRanges()
window.document.body.removeChild(span)

return success
? Promise.resolve()
: Promise.reject(new DOMException('The request is not allowed', 'NotAllowedError'))
}