Javascript复制内容到剪贴板

117 阅读1分钟

Javascript复制内容到剪贴板,解决navigator.clipboard Cannot read property 'writeText' of undefined

复制到剪贴板有两种方式:
1、navigator.clipboard.writeText(downloadUrl)

navigator.clipboard.writeText(downloadUrl).then(_ => {
              this.$notify({
                type: 'success',
                message: '图片地址已复制到剪贴板',
                duration: 5000
              })
            })

2、document.execCommand('copy')

const textArea = document.createElement('textarea')
            textArea.value = downloadUrl
            // 使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()
              this.$notify({
                type: 'success',
                message: '图片地址已复制到剪贴板',
                duration: 5000
              })
            })

如果我们在开发时浏览器识别到是非安全域,那么第一种就会报错:

navigator.clipboard Cannot read property 'writeText' of undefined

建议使用try {} catch(error) {}

          try {
            navigator.clipboard.writeText(downloadUrl).then(_ => {
              this.$notify({
                type: 'success',
                message: '图片地址已复制到剪贴板',
                duration: 5000
              })
            })
          } catch (error) {
            // 创建text area
            const textArea = document.createElement('textarea')
            textArea.value = downloadUrl
            // 使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()
              this.$notify({
                type: 'success',
                message: '图片地址已复制到剪贴板',
                duration: 5000
              })
            })
          }