使用navigator.clipboard.readtext开发的时候有用,编译后测试却不生效
- 当然,
navigator.clipboard.writeText
复制也不会生效~
原因
- 原因就是在本地的时候都是安全域名,编辑后在服务器上测试的时候可能使用的就是不安全域名了(比如
http
) - 安全域包括本地访问与开启TLS安全认证的地址,如 https 协议的地址、127.0.0.1 或 localhost 。
解决
-
使用
clipboard.js
,官网https://clipboardjs.com/,具体怎么用看https://www.npmjs.com/package/clipboard -
使用
window.isSecureContext
判断集合document.execCommand
使用(不过document.execCommand
废弃了,不推荐使用)function copyValue = (value) => { value = value + ""; if(window.isSecureContext){ navigator.clipboard.writeText(value).then(res=>{ message.success('复制成功'); }) } //不安全域使用 else{ const textArea = document.createElement('textarea'); document.body.appendChild(textArea); textArea.textContent = value; //选择 textArea.select(); //复制 document.execCommand && document.execCommand('copy'); message.success('复制成功'); } }