Nico Haegens
Nico Haegens

Reputation: 163

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:

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?

Upvotes: 1

Views: 1003

Answers (1)

Tschallacka
Tschallacka

Reputation: 28722

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

Upvotes: 2

Related Questions