0

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>
tonitone120
  • 1,920
  • 3
  • 8
  • 25
  • https://stackoverflow.com/questions/60581285/execcommand-is-now-obsolete-whats-the-alternative – Italo Hernández Feb 19 '21 at 17:46
  • 1
    Your example code works fine; just not inside an IFRAME (like StackOverflow's code snippets). I pasted it into my browser console in Chrome and had no issue. More information about when you can use the Clipboard API here: https://www.sitepoint.com/clipboard-api/ – Jon Uleis Feb 19 '21 at 17:48
  • Thanks for that @JohnUleis big help – tonitone120 Feb 19 '21 at 18:18

1 Answers1

0

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>
quicVO
  • 778
  • 4
  • 13