Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find out why queryCommandEnabled returns false

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);
like image 220
Marcus Avatar asked Mar 01 '16 10:03

Marcus


1 Answers

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>
like image 150
Herman Andres Figueroa Avatar answered Oct 15 '22 19:10

Herman Andres Figueroa