Files
deerflow-code/frontend-web/src/core/clipboard.ts
T

45 lines
1.2 KiB
TypeScript

export async function copyTextToClipboard(text: string): Promise<void> {
let clipboardError: unknown;
if (typeof navigator !== "undefined" && navigator.clipboard?.writeText) {
try {
await navigator.clipboard.writeText(text);
return;
} catch (error) {
clipboardError = error;
}
}
if (typeof document === "undefined" || !document.body) {
throw clipboardError instanceof Error
? clipboardError
: new Error("Clipboard is not available");
}
const textarea = document.createElement("textarea");
textarea.value = text;
textarea.setAttribute("readonly", "");
textarea.style.position = "fixed";
textarea.style.top = "0";
textarea.style.left = "0";
textarea.style.width = "1px";
textarea.style.height = "1px";
textarea.style.opacity = "0";
document.body.appendChild(textarea);
textarea.focus();
textarea.select();
textarea.setSelectionRange(0, textarea.value.length);
try {
const copied = document.execCommand("copy");
if (!copied) {
throw clipboardError instanceof Error
? clipboardError
: new Error("Copy command failed");
}
} finally {
textarea.remove();
}
}