Files
sencho/frontend/src/lib/clipboard.ts
T
Anso 4c35226719 fix(frontend): make copy buttons work over plain HTTP (#757)
The Clipboard API requires a secure context, so navigator.clipboard is
undefined when Sencho is accessed over HTTP on a LAN IP. Most copy
buttons therefore failed silently and a few even fired success toasts
without writing anything to the clipboard.

Extract a shared copyToClipboard helper that prefers the modern API in
secure contexts and falls back to a hidden-textarea execCommand path
otherwise, then route every existing call site through it.
2026-04-24 22:26:12 -04:00

44 lines
1.2 KiB
TypeScript

/**
* Copy text to the clipboard with a fallback for non-secure contexts.
*
* The Clipboard API (`navigator.clipboard`) is only available in secure
* contexts (HTTPS, localhost, or 127.0.0.1). Self-hosted Sencho is commonly
* accessed over plain HTTP on LAN IPs, so we fall back to the legacy
* `document.execCommand('copy')` path when the modern API is unavailable
* or rejects.
*
* Rejects only when both paths fail.
*/
export async function copyToClipboard(text: string): Promise<void> {
if (
typeof navigator !== 'undefined' &&
navigator.clipboard &&
typeof window !== 'undefined' &&
window.isSecureContext
) {
try {
await navigator.clipboard.writeText(text);
return;
} catch {
// fall through to legacy fallback
}
}
const ta = document.createElement('textarea');
ta.value = text;
ta.setAttribute('readonly', '');
ta.style.position = 'fixed';
ta.style.top = '0';
ta.style.left = '0';
ta.style.opacity = '0';
document.body.appendChild(ta);
ta.focus();
ta.select();
try {
const ok = document.execCommand('copy');
if (!ok) throw new Error('execCommand copy returned false');
} finally {
document.body.removeChild(ta);
}
}