25 lines
767 B
JavaScript
25 lines
767 B
JavaScript
export async function copyLiveText(value, {
|
|
clipboard = navigator.clipboard,
|
|
documentRef = document,
|
|
} = {}) {
|
|
const text = String(value)
|
|
if (clipboard?.writeText) {
|
|
try { await clipboard.writeText(text); return }
|
|
catch { /* Older or restricted browsers can still support a selection copy. */ }
|
|
}
|
|
const previousFocus = documentRef.activeElement
|
|
const input = documentRef.createElement('textarea')
|
|
input.value = text
|
|
input.readOnly = true
|
|
input.style.position = 'fixed'
|
|
input.style.left = '-9999px'
|
|
documentRef.body.appendChild(input)
|
|
try {
|
|
input.select()
|
|
if (!documentRef.execCommand('copy')) throw new Error('Clipboard copy failed')
|
|
} finally {
|
|
input.remove()
|
|
previousFocus?.focus?.({ preventScroll: true })
|
|
}
|
|
}
|