How can I copy text to the clipboard with JavaScript?

All Youtube tutorials seem to teach the now deprecated Document.execCommand(). I had a go trying it as the example goes on this MDN website. Maybe there’s another way?

navigator.permissions.query({name: "clipboard-write"}).then(result => {
  if (result.state == "granted" || result.state == "prompt") {
    /* write to the clipboard now */
    console.log("safe");
  }
});

let button = document.querySelector('button');

button.addEventListener('click', (e) => {
    let data = "red";
    navigator.clipboard.writeText(data).then(function() {
    /* success */
      console.log("success", data);
    }, function() {
      console.log("fail")
    /* failure */
    });
});
<button>Click me</button>

6 thoughts on “How can I copy text to the clipboard with JavaScript?”

  1. Try this:

    var copyText = document.getElementById("your-button-id");
    
    copyText.select();
    copyText.setSelectionRange(0, 99999);
    document.execCommand("copy");
    
    Reply
  2. Sure, you can copy text to the clipboard just like you did in your question and also using await/async. Try this out below. I didn’t include the query because browsers like chrome don’t always return the correct permission status.

    let button = document.querySelector('button');
    button.onclick = async (e) => {
        let data = "red";
        try {
            await navigator.clipboard.writeText(data);
            console.log("all good")
        }
        catch(err) {
            console.log(err);
        }
    }
    <button>Click Me!</button>
    Reply

Leave a Comment