找出queryCommandEnabled返回false的原因

时间:2016-03-01 10:05:14

标签: javascript angularjs google-chrome clipboard

我正在尝试使用角色应用程序中的JS将内容复制到剪贴板。

不幸的是,document.queryCommandEnabled("copy")会一直返回false。有没有办法理解为什么浏览器拒绝执行命令?启用命令的标准是什么?

代码:

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;
}

我在运行此功能之前测试命令是否已启用:

if(document.queryCommandEnabled("copy")) // Always return false
    executeCopy(text_value);

1 个答案:

答案 0 :(得分:0)

document.queryCommandEnabled(" copy")命令在有选择时返回true,否则返回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>
&#13;
&#13;
&#13;

我们必须做出选择以使其正常工作

&#13;
&#13;
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");
    }
}
&#13;
<html>
  <head></head>
  <body>
  <input type="button" onclick="copyText('Herman')" value="s">
  </body>
</html>
&#13;
&#13;
&#13;

根据浮躁的哲学家评论,使用 document.queryCommandSupported(command);验证命令是否可以在浏览器实例中运行

&#13;
&#13;
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");
}
&#13;
<html>
  <head></head>
  <body>
    <input type="button" value="Copy" onclick="doCopy()">
  </body>
</html>
&#13;
&#13;
&#13;