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.
The replacement is the Clipboard API.
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.
The execCommand() method is deprecated. Do NOT use it. The applets property returns an empty HTMLCollection in all new browsers.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With