feat: add copyToClipboard() utility with execCommand fallback

This commit is contained in:
Siddharth Kumar Sah
2026-04-04 16:25:25 +08:00
parent f61ab9f85c
commit 19ce303123
2 changed files with 52 additions and 2 deletions
+21
View File
@@ -13,3 +13,24 @@ export function generateId(): string {
const hex = Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("");
return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
}
export async function copyToClipboard(text: string): Promise<boolean> {
try {
await navigator.clipboard.writeText(text);
return true;
} catch {
try {
const textarea = document.createElement("textarea");
textarea.value = text;
textarea.style.position = "fixed";
textarea.style.opacity = "0";
document.body.appendChild(textarea);
textarea.select();
const ok = document.execCommand("copy");
document.body.removeChild(textarea);
return ok;
} catch {
return false;
}
}
}