1
0
Fork 0
mirror of synced 2024-10-01 09:38:55 +13:00

Fix copy to clipboard not working without a secure context and add better notifications

This commit is contained in:
Andrew Kingston 2022-02-04 08:50:36 +00:00
parent 47dc1ac540
commit 03b3049572

View file

@ -8,10 +8,35 @@
copyToClipboard(value)
}
function copyToClipboard(value) {
navigator.clipboard.writeText(value).then(() => {
notifications.success("Copied")
const copyToClipboard = value => {
return new Promise(res => {
if (navigator.clipboard && window.isSecureContext) {
// Try using the clipboard API first
navigator.clipboard.writeText(value).then(res)
} else {
// Fall back to the textarea hack
let textArea = document.createElement("textarea")
textArea.value = value
textArea.style.position = "fixed"
textArea.style.left = "-9999px"
textArea.style.top = "-9999px"
document.body.appendChild(textArea)
textArea.focus()
textArea.select()
document.execCommand("copy")
textArea.remove()
res()
}
})
.then(() => {
notifications.success("Copied to clipboard")
})
.catch(() => {
notifications.error(
"Failed to copy to clipboard. Check the dev console for the value."
)
console.warn("Failed to copy the value", value)
})
}
</script>