34 lines
829 B
TypeScript
34 lines
829 B
TypeScript
/**
|
|
* Copies text to the clipboard with a fallback for non-secure contexts (HTTP).
|
|
*/
|
|
export async function copyTextToClipboard(text: string): Promise<boolean> {
|
|
const value = text ?? '';
|
|
if (!value) return false;
|
|
|
|
try {
|
|
if (navigator.clipboard?.writeText) {
|
|
await navigator.clipboard.writeText(value);
|
|
return true;
|
|
}
|
|
} catch {
|
|
// Fall through to legacy path (common on HTTP origins).
|
|
}
|
|
|
|
try {
|
|
const ta = document.createElement('textarea');
|
|
ta.value = value;
|
|
ta.setAttribute('readonly', '');
|
|
ta.style.position = 'fixed';
|
|
ta.style.left = '-9999px';
|
|
ta.style.top = '0';
|
|
document.body.appendChild(ta);
|
|
ta.focus();
|
|
ta.select();
|
|
const ok = document.execCommand('copy');
|
|
document.body.removeChild(ta);
|
|
return ok;
|
|
} catch {
|
|
return false;
|
|
}
|
|
}
|