找出queryCommandEnabled返回false的原因

Mar*_*cus 9 javascript clipboard google-chrome angularjs

我试图在角度应用程序中使用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;
}
Run Code Online (Sandbox Code Playgroud)

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

if(document.queryCommandEnabled("copy")) // Always return false
    executeCopy(text_value);
Run Code Online (Sandbox Code Playgroud)

Her*_*roa 2

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();
}
Run Code Online (Sandbox Code Playgroud)
<html>
  <head></head>
  <body>
  <input type="button" onclick="doCopy('Herman')" value="s">
  </body>
</html>
Run Code Online (Sandbox Code Playgroud)

我们必须做出选择才能正常工作

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");
    }
}
Run Code Online (Sandbox Code Playgroud)
<html>
  <head></head>
  <body>
  <input type="button" onclick="copyText('Herman')" value="s">
  </body>
</html>
Run Code Online (Sandbox Code Playgroud)

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

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");
}
Run Code Online (Sandbox Code Playgroud)
<html>
  <head></head>
  <body>
    <input type="button" value="Copy" onclick="doCopy()">
  </body>
</html>
Run Code Online (Sandbox Code Playgroud)