在 Chrome 的 DevTools 控制台下执行 navigator.clipboard 返回 undefined,经查找资料发现是浏览器禁用了非安全域的 navigator.clipboard 对象,哪些地址是安全的呢?
安全域包括本地访问与开启TLS安全认证的地址,如 https 协议的地址、127.0.0.1 或 localhost 。
所以本文就是作一个兼容写法,在安全域下使用 navigator.clipboard 提升效率,非安全域退回到 document.execCommand('copy'); 保证功能可用。
fastadmin框架:
//复制功能
$("#copy").on('click',function (){
const copyText = document.getElementById("c-number");
copyText.select();
// copyText.setSelectionRange(0, 99999);
// document.execCommand('copy');
handleCopyValue(copyText.value)
.then(() => {
Backend.api.toastr.success('房源编号复制成功');
})
.catch(() => {
Backend.api.toastr.error('自动复制失败,请手动复制');
});
});
function handleCopyValue(text) {
//浏览器禁用了非安全域的 navigator.clipboard 对象
//在线上环境会报错 TypeError: Cannot read properties of undefined (reading 'writeText')
if (!navigator.clipboard && window.isSecureContext) {
return navigator.clipboard.writeText(text)
} else {
// 判断是否支持拷贝
if (!document.execCommand('copy')) return Promise.reject()
// 创建标签,并隐藏
const textArea = document.createElement('textarea')
textArea.style.position = 'fixed'
textArea.style.top = textArea.style.left = '-100vh'
textArea.style.opacity = '0'
textArea.value = text
document.body.appendChild(textArea)
// 聚焦、复制
textArea.focus()
textArea.select()
return new Promise((resolve, reject) => {
// 不知为何,必须写这个三目,不然copy不上
document.execCommand('copy') ? resolve() : reject()
textArea.remove()
})
}
}
引用文档:https://blog.csdn.net/zero77ld/article/details/127967854