1

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")
  • 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. Any idea how to get around this?

Chris G
  • 7,957
  • 4
  • 17
  • 29
Nico Haegens
  • 155
  • 1
  • 8
  • 1
    Possible duplicate of [How do I copy to the clipboard in JavaScript?](https://stackoverflow.com/questions/400212/how-do-i-copy-to-the-clipboard-in-javascript) – Daan Nov 27 '18 at 10:25

1 Answers1

2

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. 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.

If you'd use clipboard.js you could use code like this:

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 );
          });
    }
}
Tschallacka
  • 24,188
  • 10
  • 79
  • 121