实现一键复制功能遇到的问题
之前做了一个项目,是仿着chat-gpt
写的,现在优化,添加了一键复制功能
function copyCode(codeToCopy) {
navigator.clipboard
.writeText(codeToCopy)
.then(() => {
ElMessage.success({
message: "复制成功",
type: "success",
});
})
.catch((err) => {
console.error("Failed to copy code: ", err);
});
}
在本地运行是可以实现的,但是放到线上会报这样的!错误:
他说navigator.clipboard
是undefined
,但是打印navigator是存在的,并且本地打印是存在navigator.clipboard
的,经查询是浏览器禁用了非安全域的 navigator.clipboard
对象。
什么是安全域呢?
安全域包括本地访问与开启TLS安全认证的地址,如 https
协议的地址、127.0.0.1
或 localhost
。
由于公司内部使用的是http协议,所以被浏览器禁用了,所以需要添加兼容性代码,在安全域下使用 navigator.clipboard
提升效率,非安全域退回到 document.execCommand('copy');
function copyCode(codeToCopy) {
if (navigator.clipboard && window.isSecureContext) { // 只能在安全域下使用 安全域包括本地访问与开启TLS安全认证的地址,如 https 协议的地址、127.0.0.1 或 localhost
// navigator clipboard 向剪贴板写文本
navigator.clipboard
.writeText(codeToCopy)
.then(() => {
ElMessage.success({
message: "复制成功",
type: "success",
});
})
.catch((err) => {
console.error("Failed to copy code: ", err);
});
} else {
// 创建text area
let textArea = document.createElement("textarea");
textArea.value = codeToCopy;
// 使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();
}).then(() => {
ElMessage.success({
message: "复制成功",
type: "success",
});
}).catch((err) => {
console.error("Failed to copy code: ", err);
});
}
}
这样就实现啦,本地环境和正式环境都可以使用啦。
至于文章中说的微信浏览器打开不生效我这边测试是没有问题的,可能是那端优化了吧。