js 复制内容到剪贴板,解决navigator.clipboard Cannot read properties of undefined (reading ‘writeText‘) |
您所在的位置:网站首页 › 复制js navigatorclipboard › js 复制内容到剪贴板,解决navigator.clipboard Cannot read properties of undefined (reading ‘writeText‘) |
之前写过一个文章,是实现了点击按钮实现复制功能,链接在此:https://blog.csdn.net/qq_58340302/article/details/123847964?spm=1001.2014.3001.5502 这个实现方法在本地运行的时候点儿问题都没有,但是! 但是将他拿到测试环境时,bug出现了,报错如下: 经查找资料发现是浏览器禁用了非安全域的 navigator.clipboard 对象。 安全域包括本地访问与开启TLS安全认证的地址,如 https 协议的地址、127.0.0.1 或 localhost 。 所以要解决这个bug就是要做一个兼容写法,在安全域下使用 navigator.clipboard 提升效率,非安全域退回到 document.execCommand('copy'); 保证功能一直可用。 // 先给要复制的文本或者按钮加上点击事件后,并将要复制的值传过来 async copyValue(val) { if (navigator.clipboard && window.isSecureContext) { // navigator clipboard 向剪贴板写文本 this.$message.success('复制成功') return navigator.clipboard.writeText(val) } else { // 创建text area const textArea = document.createElement('textarea') textArea.value = val // 使text area不在viewport,同时设置不可见 document.body.appendChild(textArea) textArea.focus() textArea.select() this.$message.success('复制成功') return new Promise((res, rej) => { // 执行复制命令并移除文本框 document.execCommand('copy') ? res() : rej() textArea.remove() }) } },运行一下,本地和测试环境都没问题啦 ~ 时隔半个多月后,又发现了bug,这个方法在微信浏览器打开是不生效的,所以又找到了个新方法,有需要的话可以参考一下vue 适配微信浏览器 实现点击按钮复制文本 clipboard_Naive_Jam的博客-CSDN博客 |
今日新闻 |
推荐新闻 |
CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3 |