Created
October 8, 2024 20:23
-
-
Save hctilg/668846544ad9569f4ca5216febbd0a68 to your computer and use it in GitHub Desktop.
Copy to clipboard with Javascript
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function copyToClipboard(text, success) { | |
if (navigator.clipboard && window.isSecureContext) { | |
return navigator.clipboard.writeText(text).then(success).catch(err => { | |
console.error('Failed to copy text: ', err); | |
}); | |
} else { | |
const textarea = document.createElement('textarea'); | |
textarea.value = text; | |
document.body.appendChild(textarea); | |
textarea.select(); | |
textarea.setSelectionRange(0, text.length); | |
document.execCommand('copy'); | |
document.body.removeChild(textarea); | |
success(); | |
} | |
} | |
copyToClipboard("Hello, world!", () => { | |
alert('Copied to clipboard'); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment