How to copy text to clipboard with Javascript easily

How to copy text to clipboard with Javascript easily

It is possible to be injured by automatic copying to the clipboard. It is therefore difficult for most browsers to do this. No one wants to be left with suspicious links or other things that could creep us out.

Any solution you find online must be activated by the user. A click.There is no solution. Flash will not automatically copy things, even if the user interacts.This is all there is to know about the Flash or JavaScript clipboard.

This post will show you how to accomplish this task using pure JavaScript. If you don’t succeed, there are solutions using flash.


1. execCommand

This implementation uses the document-exec-command function. This function is available in the following browsers.

  • IE10.
  • Google Chrome >=43
  • Mozilla Firefox >=41.
  • Opera >=29.

It’s really easy: the exec-command will natively copy the text within the text-area to the clipboard.


If the action is not initiated by the user, the code will not work. Inject via console won’t work. The code will fail if the text-area is not visible (display=none).

function setClipboardText(text){
    var id = "mycustom-clipboard-textarea-hidden-id";
    var existsTextarea = document.getElementById(id);

        console.log("Creating textarea");
        var textarea = document.createElement("textarea"); = id;
        // Place in top-left corner of screen regardless of scroll position. = 'fixed'; = 0; = 0;

        // Ensure it has a small width and height. Setting to 1px / 1em
        // doesn't work as this gives a negative w/h on some browsers. = '1px'; = '1px';

        // We don't need padding, reducing the size if it does flash render. = 0;

        // Clean up any borders. = 'none'; = 'none'; = 'none';

        // Avoid flash of white box if rendered for any reason. = 'transparent';
        console.log("The textarea now exists :)");
        existsTextarea = document.getElementById(id);
        console.log("The textarea already exists :3")

    existsTextarea.value = text;;

    try {
        var status = document.execCommand('copy');
            console.error("Cannot copy text");
            console.log("The text is now on the clipboard");
    } catch (err) {
        console.log('Unable to copy.');

Use the following fiddle to play:

var copyTextareaBtn = document.querySelector('.js-textareacopybtn');

copyTextareaBtn.addEventListener('click', function(event) {
  var copyTextarea = document.querySelector('.js-copytextarea');;

  try {
    var successful = document.execCommand('copy');
    var msg = successful ? 'successful' : 'unsuccessful';
    console.log('Copying text command was ' + msg);
  } catch (err) {
    console.log('Oops, unable to copy');

2. Using Clipboard.js

Everyone loves libraries. You should also love libraries. It makes life easier and has been tried for many. Clipboard.js, a lightweight and modern way to copy text from Flash to a clipboard is called __S.30__.

Use the following code to initialize clipboard.js

<button class="btn" data-clipboard-text="Este texto sera copiado">Copiar texto</button>

var clipboard = new Clipboard('.btn');

clipboard.on('success', function(e) {'Accion:', e.action);'Texto:', e.text);'Trigger:', e.trigger);


clipboard.on('error', function(e) {
    console.error('Accion:', e.action);
    console.error('Trigger:', e.trigger);

Clipboard constructor expects a first parameter of dom selector. All items of class btn with a dom selector as first parameter will copy the text to the clipboard. This library also relies on exec-command.

Fallback with flash

You won’t have any other options if you absolutely need to add this feature to your website or provide support for older browsers.

You don’t have to worry about messing up your code. ZeroClipboard can help you create a clean solution. You can see a working demo on the plugin’s homepage.

This solution has its limitations. Flash and browser security restrictions can make this solution difficult to use.This clipboard injection is only possible when the user clicks the invisible Flash movie. JavaScript’s simulated click event will not suffice, as this would allow clipboard poisoning.

ZeroClipboard can be implemented in as easy as:

<!DOCTYPE html>
 <!-- Get a copy of ZeroClibboard.js in the official repository 
      Note that the .swf core file needs to be in the same path that .js file
      The flash file will be automatically loaded by the plugin.
 <script src="ZeroClipboard.js"></script>
 <button id="copy-button" data-clipboard-text="Copy Me!" title="Click to copy me.">Copy to Clipboard</button>
    var client = new ZeroClipboard( document.getElementById("copy-button") );
    // Wrap the events inside the ready event of the swf clipboard
    client.on( "ready", function( readyEvent ) {
        // alert( "ZeroClipboard SWF is ready!" );

        client.on( "aftercopy", function( event ) {
           // `this` === `client`
           // `` === the element that was clicked
  = "none";
           alert("Copied text to clipboard: " +["text/plain"] );

Have fun!