fix: 修复 HTTP 环境下复制功能失败的问题
问题: - navigator.clipboard 只在 HTTPS 下可用 - HTTP 环境(IP 访问)会报错 Cannot read properties of undefined 解决方案: - 创建兼容的 copyToClipboard 函数 - 优先尝试 navigator.clipboard (HTTPS) - 降级到 document.execCommand (HTTP 也可用) - 统一处理 copyJSON 和 copyConfig 两处复制功能 - 失败时提示用户手动复制
This commit is contained in:
+41
-4
@@ -676,14 +676,47 @@
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 通用复制函数(兼容 HTTP 和 HTTPS)
|
||||||
|
function copyToClipboard(text) {
|
||||||
|
// 方法1: 尝试 navigator.clipboard (HTTPS)
|
||||||
|
if (navigator.clipboard && navigator.clipboard.writeText) {
|
||||||
|
return navigator.clipboard.writeText(text)
|
||||||
|
.then(() => true)
|
||||||
|
.catch(() => false);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 方法2: 使用传统的 execCommand (HTTP 也可用)
|
||||||
|
return new Promise((resolve) => {
|
||||||
|
const textarea = document.createElement('textarea');
|
||||||
|
textarea.value = text;
|
||||||
|
textarea.style.position = 'fixed';
|
||||||
|
textarea.style.left = '-9999px';
|
||||||
|
textarea.style.top = '0';
|
||||||
|
document.body.appendChild(textarea);
|
||||||
|
|
||||||
|
try {
|
||||||
|
textarea.select();
|
||||||
|
textarea.setSelectionRange(0, 99999);
|
||||||
|
const success = document.execCommand('copy');
|
||||||
|
document.body.removeChild(textarea);
|
||||||
|
resolve(success);
|
||||||
|
} catch (err) {
|
||||||
|
document.body.removeChild(textarea);
|
||||||
|
resolve(false);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
// 复制 JSON
|
// 复制 JSON
|
||||||
function copyJSON() {
|
function copyJSON() {
|
||||||
if (currentViewData) {
|
if (currentViewData) {
|
||||||
const text = JSON.stringify(currentViewData, null, 2);
|
const text = JSON.stringify(currentViewData, null, 2);
|
||||||
navigator.clipboard.writeText(text).then(() => {
|
copyToClipboard(text).then((success) => {
|
||||||
|
if (success) {
|
||||||
showToast('JSON 已复制到剪贴板');
|
showToast('JSON 已复制到剪贴板');
|
||||||
}).catch(() => {
|
} else {
|
||||||
showToast('复制失败', 'error');
|
showToast('复制失败,请手动选择复制', 'error');
|
||||||
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -694,8 +727,12 @@
|
|||||||
const response = await fetch(`/api/data/copy/${tag}`);
|
const response = await fetch(`/api/data/copy/${tag}`);
|
||||||
const data = await response.json();
|
const data = await response.json();
|
||||||
|
|
||||||
await navigator.clipboard.writeText(data.copy_text);
|
const success = await copyToClipboard(data.copy_text);
|
||||||
|
if (success) {
|
||||||
showToast('配置已复制到剪贴板');
|
showToast('配置已复制到剪贴板');
|
||||||
|
} else {
|
||||||
|
showToast('复制失败,请手动选择复制', 'error');
|
||||||
|
}
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
showToast('复制失败:' + error.message, 'error');
|
showToast('复制失败:' + error.message, 'error');
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user