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

user984003 :

I just saw on the Mozilla page that execCommand() is obsolete https://developer.mozilla.org/en-US/docs/Web/API/Document/execCommand

"This feature is obsolete. Although it may still work in some browsers, its use is discouraged since it could be removed at any time. Try to avoid using it."

This is what I currently use to copy text to the user's clipboard when the user clicks a "copy text" button. Is there another way to do it?

 var input = // input element with the text
 input.focus();
 input.setSelectionRange(0,99999);
 document.execCommand("copy");
 input.blur();

Edit: This How do I copy to the clipboard in JavaScript? does not answer the question. It suggests the same obsolete solution.

user984003 :

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.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=6910&siteId=1