I am trying to copy content to clipboard using JS in an angular app.
Unfortunately, document.queryCommandEnabled("copy") will consistently return false. Is there any way to understand why the browser denies the command to be executed? What are the criterion to enable the command?
Code:
function copyText(text) {
var input = document.createElement('textarea');
document.body.appendChild(input);
input.value = text;
input.focus();
input.select();
var success = document.execCommand('Copy');
input.remove();
return success;
}
I test if the command is enabled before I run this function:
if(document.queryCommandEnabled("copy")) // Always return false
executeCopy(text_value);
The document.queryCommandEnabled ("copy") command returns true when there is a selection otherwise it will return false
function doCopy(){
if(document.queryCommandEnabled("copy")){
copyText("Hola")
}else{
alert("Never Fired");
}
}
function copyText(text) {
var input = document.createElement('textarea');
document.body.appendChild(input);
input.value = text;
input.focus();
input.select();
var success = document.execCommand('Copy');
input.remove();
}
<html>
<head></head>
<body>
<input type="button" onclick="doCopy('Herman')" value="s">
</body>
</html>
we must make a selection so that it works correctly
function copyText(text) {
var input = document.createElement('textarea');
document.body.appendChild(input);
input.value = text;
input.focus();
input.select();
if(document.queryCommandEnabled("copy")){
var success = document.execCommand('Copy');
input.remove();
alert("Copy Ok");
}else{
alert("queryCommandEnabled is false");
}
}
<html>
<head></head>
<body>
<input type="button" onclick="copyText('Herman')" value="s">
</body>
</html>
according to Blundering Philosopher's comment, use document.queryCommandSupported(command); to validate if the command is possible to run in the browser instance
function doCopy(){
if(document.queryCommandSupported("copy")){
copyText("Hello")
}else{
alert("Never Fired");
}
}
function copyText(text) {
var input = document.createElement('textarea');
document.body.appendChild(input);
input.value = text;
input.focus();
input.select();
var success = document.execCommand('Copy');
input.remove();
alert("Copy Ok");
}
<html>
<head></head>
<body>
<input type="button" value="Copy" onclick="doCopy()">
</body>
</html>
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