Spaces:
Runtime error
Runtime error
File size: 1,560 Bytes
cd8bd0a | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 | /**
* Clipboard utility with HTTP/HTTPS fallback.
* navigator.clipboard.writeText() requires HTTPS (secure context).
* For HTTP deployments, falls back to execCommand('copy').
*/
/**
* Copy text to clipboard with automatic HTTPS/HTTP fallback.
* Works in both secure (HTTPS) and non-secure (HTTP) contexts.
* @param text - Text to copy to clipboard
* @returns true if copy succeeded, false otherwise
*/
export async function copyToClipboard(text: string): Promise<boolean> {
// Method 1: Clipboard API
// Works on HTTPS, localhost (treated as secure context), and some browsers
// even on HTTP. Try unconditionally — the catch handles failures.
if (typeof navigator !== "undefined" && navigator.clipboard) {
try {
await navigator.clipboard.writeText(text);
return true;
} catch {
// Fall through to execCommand fallback
}
}
// Method 2: Legacy execCommand fallback (works on HTTP)
if (typeof document !== "undefined" && document.body) {
const textArea = document.createElement("textarea");
textArea.value = text;
textArea.style.cssText = "position:fixed;top:0;left:-9999px;opacity:0;pointer-events:none;";
let appended = false;
try {
document.body.appendChild(textArea);
appended = true;
textArea.focus();
textArea.select();
return document.execCommand("copy");
} catch {
return false;
} finally {
if (appended && document.body.contains(textArea)) {
document.body.removeChild(textArea);
}
}
}
return false;
}
|