Files

39 lines
1009 B
TypeScript
Raw Permalink Normal View History

2026-10-05 18:10:18 -04:00
/** Falls back to execCommand('copy') where the Clipboard API is unavailable, such as over plain HTTP. */
export default async function copyToClipboard(text: string): Promise<boolean> {
if (window.isSecureContext && navigator.clipboard) {
try {
await navigator.clipboard.writeText(text);
2026-10-08 16:53:20 -04:00
2026-10-05 18:10:18 -04:00
return true;
} catch {
// Fall back to execCommand.
}
}
const textarea = document.createElement('textarea');
2026-10-08 16:53:20 -04:00
2026-10-05 18:10:18 -04:00
textarea.value = text;
textarea.setAttribute('readonly', '');
textarea.style.position = 'fixed';
textarea.style.top = '0';
textarea.style.left = '0';
textarea.style.opacity = '0';
textarea.style.pointerEvents = 'none';
document.body.appendChild(textarea);
textarea.focus();
textarea.select();
let succeeded = false;
2026-10-08 16:53:20 -04:00
2026-10-05 18:10:18 -04:00
try {
succeeded = document.execCommand('copy');
} catch {
succeeded = false;
}
document.body.removeChild(textarea);
return succeeded;
}