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.

这种情况是浏览器的安全控制,需要用户主动触发
在这里插入图片描述

Logo

有“AI”的1024 = 2048,欢迎大家加入2048 AI社区

更多推荐