mirror of
https://github.com/eduardolat/pgbackweb.git
synced 2026-01-25 05:58:29 -06:00
Add initCopyFunction to app.js for copying text to clipboard
This commit is contained in:
@@ -1,7 +1,9 @@
|
||||
import { initNotyf } from './init-notyf.js'
|
||||
import { initHTMXTriggers } from './init-htmx-triggers.js'
|
||||
import { initAlpineComponents } from './init-alpine-components.js'
|
||||
import { initCopyFunction } from './init-copy-function.js'
|
||||
|
||||
initNotyf()
|
||||
initHTMXTriggers()
|
||||
initAlpineComponents()
|
||||
initCopyFunction()
|
||||
|
||||
47
internal/view/static/js/init-copy-function.js
Normal file
47
internal/view/static/js/init-copy-function.js
Normal file
@@ -0,0 +1,47 @@
|
||||
export function initCopyFunction () {
|
||||
function copyToClipboard (textToCopy) {
|
||||
const successMessage = 'Text copied'
|
||||
const errorMessage = 'Error copying text'
|
||||
|
||||
/* First, try the modern approach */
|
||||
if (navigator.clipboard && window.isSecureContext) {
|
||||
return navigator.clipboard
|
||||
.writeText(textToCopy)
|
||||
.then(() => {
|
||||
toaster.success(successMessage)
|
||||
})
|
||||
.catch((err) => {
|
||||
console.error(errorMessage, err)
|
||||
toaster.error(errorMessage)
|
||||
})
|
||||
}
|
||||
|
||||
/* Fallback: use execCommand("copy") method */
|
||||
const textArea = document.createElement('textarea')
|
||||
textArea.value = textToCopy
|
||||
|
||||
textArea.style.position = 'fixed'
|
||||
textArea.style.left = '-9999px'
|
||||
textArea.style.top = '-9999px'
|
||||
document.body.appendChild(textArea)
|
||||
textArea.focus()
|
||||
textArea.select()
|
||||
|
||||
try {
|
||||
const successful = document.execCommand('copy')
|
||||
if (successful) {
|
||||
toaster.success(successMessage)
|
||||
} else {
|
||||
console.error('Fallback', errorMessage)
|
||||
toaster.error(errorMessage)
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('Fallback', errorMessage, err)
|
||||
toaster.error(errorMessage)
|
||||
}
|
||||
|
||||
document.body.removeChild(textArea)
|
||||
}
|
||||
|
||||
window.copyToClipboard = copyToClipboard
|
||||
}
|
||||
Reference in New Issue
Block a user