Skip to content

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)
}
See also  How to find type of variable in JavaScript?

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.