Copy text to clipboard now that execCommand(“copy”) is obsolete

From Klaycon’s comment to the question. The replacement is the Clipboard API. It is not implemented in all browsers, but most.

https://developer.mozilla.org/en-US/docs/Web/API/Clipboard_API

// In this example, the text to copy would be in an element with id = textcopy

var text_to_copy = document.getElementById("textcopy").innerHTML;

if (!navigator.clipboard){
    // use old commandExec() way
} else{
    navigator.clipboard.writeText(text_to_copy).then(
        function(){
            alert("yeah!"); // success 
        })
      .catch(
         function() {
            alert("err"); // error
      });
}    

For some browsers (like Firefox) this only works when initiated by a user action. So, put the code inside a button listener, for example.

I tested this (Feb 2020) in (Windows) Chrome, Firefox, new Edge, Opera, iOS Safari, iOS Chrome, iOS app webview. Clipboard writeText works great.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)