Files
model-platform/frontend/app/lib/clipboard.ts
T
2026-08-17 17:31:12 +08:00

32 lines
872 B
TypeScript

/**
* 复制文本到剪贴板 - 兼容 HTTP 和 HTTPS 环境
*
* 在 HTTPS 环境下使用现代 Clipboard API
* 在 HTTP 环境下降级使用 execCommand 方案
*
* @param text - 要复制的文本
* @returns Promise<void>
*/
export async function copyToClipboard(text: string): Promise<void> {
// 优先使用现代 Clipboard API (HTTPS 环境)
if (navigator.clipboard?.writeText) {
await navigator.clipboard.writeText(text);
return;
}
// 降级方案:execCommand (HTTP 环境 / 旧浏览器)
const textarea = document.createElement("textarea");
textarea.value = text;
textarea.style.position = "fixed";
textarea.style.opacity = "0";
textarea.style.left = "-9999px";
document.body.appendChild(textarea);
textarea.select();
try {
document.execCommand("copy");
} finally {
document.body.removeChild(textarea);
}
}