简体   繁体   English

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

[英]How to copy text contents in body to clipboard

I need to copy all the text in my body to the clipboard, here is what I've tried so far: 我需要将体内的所有文本复制到剪贴板,这是到目前为止我尝试过的操作:

  • selecting the text nodes and then the command document.execCommand("copy") 选择文本节点,然后选择命令document.execCommand("copy")
  • selecting the text nodes and then using the keyboard dispatcher: 选择文本节点,然后使用键盘调度程序:

     $("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})); 

No errors pop up. 没有错误弹出。 I've read in the Chromium documentation that the copy command is disabled for security reasons. 我已经在Chromium文档中阅读到,出于安全原因,复制命令已禁用。 Any idea how to get around this? 任何想法如何解决这个问题?

Copying into clipboard will only work on a true user interaction. 复制到剪贴板仅适用于真正的用户交互。 Without a true user interaction it will usually fail. 如果没有真正的用户交互,它将通常失败。 I believe it's for security measures. 我相信这是为了安全措施。 So hook it on a click event. 因此,将其挂接到click事件上。 Then I also suggest you use a library like clipboard.js that sorts out trouble with different browsers and allows you to put in the html variety and plaintext copy. 然后,我还建议您使用诸如剪贴板 .js之类的库,该库可以解决不同浏览器的问题,并允许您放入html和纯文本副本。

If you'd use clipboard.js you could use code like this: 如果使用剪贴板.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 );
          });
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM