关于navigator.clipboard使用的问题

navigator.clipboard.writeText 可用作复制功能,使用方法如下

navigator.clipboard.writeText('复制的内容')

该方法对部分浏览器不支持
浏览器兼容

image.png

同时,该方法也不支持非https安全模式
例如开发时容易遇见的问题,本地调试时,使用该方法可以正在使用,但部署到非安全域http环境中,此时会复制失败,控制台打印navigator.clipboard也会提示undefined。
此时我们需要应对这种情况做兼容处理:

function copyToClipboard(textToCopy) {
      // navigator clipboard 需要在htts安全域中
      if (navigator.clipboard && window.isSecureContext) {
        return navigator.clipboard.writeText(textToCopy)
      } else {
        // http模式下或部分浏览器,不支持navigator.clipboard
        // 创建text area
        let textArea = document.createElement('textarea')
        textArea.value = textToCopy
        // 使text area不在viewport,同时设置不可见
        textArea.style.position = 'absolute'
        textArea.style.opacity = 0
        textArea.style.left = '-999999px'
        textArea.style.top = '-999999px'
        document.body.appendChild(textArea)
        textArea.focus()
        textArea.select()
        return new Promise((res, rej) => {
          // 执行复制命令并移除文本框
          document.execCommand('copy') ? res() : rej()
          textArea.remove()
        })
      }
    },
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容