Files
backerup-website/frontend/lib/clipboard.ts
T

34 lines
1.1 KiB
TypeScript

/**
* Copies text to the clipboard.
*
* Tries the modern Clipboard API first (requires secure context / HTTPS).
* Falls back to the legacy textarea + execCommand technique, which works on
* plain HTTP and private-IP origins where navigator.clipboard is unavailable.
*/
export async function copyText(text: string): Promise<void> {
// Modern path — secure context (HTTPS or localhost)
if (typeof navigator !== 'undefined' && navigator.clipboard?.writeText) {
try {
await navigator.clipboard.writeText(text)
return
} catch {
// Fall through to legacy method
}
}
// Legacy fallback — works on HTTP / private IPs
const el = document.createElement('textarea')
el.value = text
// Keep it out of the viewport so it doesn't flash
el.style.cssText = 'position:fixed;top:0;left:0;width:1px;height:1px;opacity:0;pointer-events:none;'
document.body.appendChild(el)
el.focus()
el.select()
try {
// eslint-disable-next-line @typescript-eslint/no-deprecated
document.execCommand('copy')
} finally {
document.body.removeChild(el)
}
}