Copy text to clipboard in JavaScript
The usual way to copy text to the clipboard is to use document.execCommand but this is a synchronous way and you need to wait for it to get completed and move on to the next step.
function copyToClipboard() { const copyText = document.getElementById("input"); copyText.select(); document.execCommand("copy"); }
That’s the new Async Clipboard API since Chrome 66 which replaces execCommand-based copy & paste. Clipboard.writeText is a well-defined permissions model and doesn’t block the page. Since this API is asynchronous, the writeText()
function returns a Promise that will be resolved or rejected depending on whether the text we passed is copied successfully:
navigator.clipboard.writeText('We Poop Code!') .then(() => { // Copied! }) .catch(err => { console.log('Oops. ERROR!', err); });
If you do not want to handle the Promises, you can write like below.
function copyToClipboard(){ navigator.clipboard.writeText(document.querySelector('#input').value) }