36 lines
1.2 KiB
TypeScript
36 lines
1.2 KiB
TypeScript
|
|
/**
|
||
|
|
* Copies `text` to the clipboard, preferring the async Clipboard API and
|
||
|
|
* falling back to a hidden-textarea + `document.execCommand('copy')` when
|
||
|
|
* the Clipboard API is unavailable or unusable (e.g. a non-secure-context
|
||
|
|
* local/dev origin, or a browser/permission that rejects the write).
|
||
|
|
* Never throws -- resolves `false` on failure so callers can show a
|
||
|
|
* visible error state instead of silently doing nothing.
|
||
|
|
*/
|
||
|
|
export async function copyToClipboard(text: string): Promise<boolean> {
|
||
|
|
try {
|
||
|
|
if (navigator.clipboard && window.isSecureContext) {
|
||
|
|
await navigator.clipboard.writeText(text);
|
||
|
|
return true;
|
||
|
|
}
|
||
|
|
} catch {
|
||
|
|
// Fall through to the legacy fallback below.
|
||
|
|
}
|
||
|
|
|
||
|
|
try {
|
||
|
|
const textarea = document.createElement('textarea');
|
||
|
|
textarea.value = text;
|
||
|
|
textarea.setAttribute('readonly', '');
|
||
|
|
textarea.style.position = 'fixed';
|
||
|
|
textarea.style.top = '-9999px';
|
||
|
|
textarea.style.left = '-9999px';
|
||
|
|
document.body.appendChild(textarea);
|
||
|
|
textarea.select();
|
||
|
|
textarea.setSelectionRange(0, textarea.value.length);
|
||
|
|
const ok = document.execCommand('copy');
|
||
|
|
document.body.removeChild(textarea);
|
||
|
|
return ok;
|
||
|
|
} catch {
|
||
|
|
return false;
|
||
|
|
}
|
||
|
|
}
|