36 lines
958 B
TypeScript
36 lines
958 B
TypeScript
export async function copyText(value: string) {
|
|||
|
|
if (typeof navigator !== 'undefined' && navigator.clipboard?.writeText) {
|
||
|
|
try {
|
||
|
|
await navigator.clipboard.writeText(value)
|
||
|
|
return
|
||
|
|
} catch {
|
||
|
|
// In insecure development contexts the Clipboard API may exist but reject.
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
if (typeof document === 'undefined' || !document.body) {
|
||
|
|
throw new Error('Clipboard is unavailable')
|
||
|
|
}
|
||
|
|
|
||
|
|
const textarea = document.createElement('textarea')
|
||
|
|
textarea.value = value
|
||
|
|
textarea.readOnly = true
|
||
|
|
textarea.setAttribute('aria-hidden', 'true')
|
||
|
|
Object.assign(textarea.style, {
|
||
|
|
position: 'fixed',
|
||
|
|
inset: '0 auto auto -9999px',
|
||
|
|
opacity: '0',
|
||
|
|
pointerEvents: 'none',
|
||
|
|
})
|
||
|
|
document.body.appendChild(textarea)
|
||
|
|
textarea.select()
|
||
|
|
|
||
|
|
try {
|
||
|
|
if (typeof document.execCommand !== 'function' || !document.execCommand('copy')) {
|
||
|
|
throw new Error('Clipboard copy failed')
|
||
|
|
}
|
||
|
|
} finally {
|
||
|
|
textarea.remove()
|
||
|
|
}
|
||
|
|
}
|