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

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

  1. function clipboardCopy (text) {
  2. if (navigator.clipboard) { // 如果浏览器兼容该 API
  3. return navigator.clipboard.writeText(text).catch(function (err) {
  4. throw (err !== undefined ? err : new DOMException('The request is not allowed', 'NotAllowedError'))
  5. })
  6. }
  7. // 或者使用 document.execCommand()
  8. // 把需要复制的文本放入 <span>
  9. const span = document.createElement('span')
  10. span.textContent = text
  11. // 保留文本样式
  12. span.style.whiteSpace = 'pre'
  13. // 把 <span> 放进页面
  14. document.body.appendChild(span)
  15. // 创建选择区域
  16. const selection = window.getSelection()
  17. const range = window.document.createRange()
  18. selection.removeAllRanges()
  19. range.selectNode(span)
  20. selection.addRange(range)
  21. // 复制文本到剪切板
  22. let success = false
  23. try {
  24. success = window.document.execCommand('copy')
  25. } catch (err) {
  26. console.log('error', err)
  27. }
  28. // 清除战场
  29. selection.removeAllRanges()
  30. window.document.body.removeChild(span)
  31. return success
  32. ? Promise.resolve()
  33. : Promise.reject(new DOMException('The request is not allowed', 'NotAllowedError'))
  34. }