Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
117
rated 0 times [  123] [ 6]  / answers: 1 / hits: 19392  / 4 Years ago, thu, february 13, 2020, 12:00:00

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.


More From » javascript

 Answers
4

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.


[#51213] Wednesday, February 5, 2020, 4 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
deonkalvinw

Total Points: 409
Total Questions: 96
Total Answers: 89

Location: Saint Pierre and Miquelon
Member since Sun, Nov 27, 2022
2 Years ago
deonkalvinw questions
Sun, Feb 6, 22, 00:00, 2 Years ago
Tue, Dec 28, 21, 00:00, 2 Years ago
Sun, Aug 22, 21, 00:00, 3 Years ago
Sun, Mar 7, 21, 00:00, 3 Years ago
;