如何将正文中的文本内容复制到剪贴板

时间:2018-11-27 10:18:06

标签: javascript clipboard chromium-embedded

我需要将体内的所有文本复制到剪贴板, 这是到目前为止我尝试过的:

  • 选择文本节点,然后选择命令document.execCommand("copy")
  • 选择文本节点,然后使用键盘调度程序:

    $("body").contents().filter(function(){return this.nodeType === 3;}).select();
    document.body.dispatchEvent(new KeyboardEvent("keyup", {bubbles: true, cancelable: false, key: "C", char: "C", ctrlKey: true}));
    

没有错误弹出。我已经在Chromium文档中阅读到,出于安全原因,复制命令已禁用。知道如何解决这个问题吗?

1 个答案:

答案 0 :(得分:1)

复制到剪贴板仅适用于真正的用户交互。如果没有真正的用户交互,它将通常失败。我相信这是为了安全措施。 因此,将其挂接到click事件上。然后,我还建议您使用clipboard.js之类的库,以解决使用不同浏览器的麻烦,并允许您放入html和纯文本副本。

如果您要使用剪贴板.js,则可以使用如下代码:

plaintext = "boo";
htmltext = "<strong>boo</strong>";
document.getElementById("copybutton").addEventListener('click', function() {
    clipboard.copy({ 
            'text/plain': plaintext,
            'text/html': htmltext
          }).then(
            function(){
                swal({
                    title: "Successfully copied",
                    text: "The thing has been put in your clipboard, happy pasting!",
                    type: "success",
                    closeOnConfirm:true,
                    confirmButtonText: "Ok",
                    timer: 1200
                });
            },
            function(err){
                window.prompt("Something went wrong with automatically copying the data to clipboard.\nPlease press CTRC + C to copy the data",plaintext );
          });
    }
}
相关问题