Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

javascript

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.

like image 322
user984003 Avatar asked Feb 13 '20 22:02

user984003


People also ask

What can I use instead of execCommand copy?

The replacement is the Clipboard API.

Why is document execCommand deprecated?

execCommand() Deprecated: This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes.

Should I use document execCommand?

The execCommand() method is deprecated. Do NOT use it. The applets property returns an empty HTMLCollection in all new browsers.

How do I copy text to clipboard?

Select the first item that you want to copy, and press CTRL+C. Continue copying items from the same or other files until you have collected all of the items that you want. The Office Clipboard can hold up to 24 items.


1 Answers

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.

like image 150
user984003 Avatar answered Oct 13 '22 20:10

user984003