Learn a couple of tricks to copy text from javascript to the clipboard and learn why it's so complicated to achieve.

How to copy text to clipboard with Javascript easily

Automatic copying to clipboard may be dangerous, therefore most browsers make it difficult to do. Nobody wants to end up with suspicious links in the clipboard or things that can creep the hell out of us.

Any possible working solution that you can find on the internet, needs to be triggered by an action of the user i.e a click. Not any solution, even with flash will copy automatically things without the user interaction. That's all you need to know related to the clipboard in Javascript or Flash.

In this post, we'll offer you different ways to achieve this task easily using pure javascript and if you can't achieve it, you'll find solutions using flash as a fallback with a clean implementation.

Javascript

1. execCommand

The first implementation uses the document execCommand function. This function is supported in the following browsers:

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

The trick is really simple, the execCommand will copy natively into the clipboard the text inside the textarea.

Important

The code will never work if the action is not triggered by the user (Only clicks). Inject via console will not work. Note that the textarea needs to be visible (display:none) will make the code fail.

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

    if(!existsTextarea){
        console.log("Creating textarea");
        var textarea = document.createElement("textarea");
        textarea.id = id;
        // Place in top-left corner of screen regardless of scroll position.
        textarea.style.position = 'fixed';
        textarea.style.top = 0;
        textarea.style.left = 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.
        textarea.style.width = '1px';
        textarea.style.height = '1px';

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

        // Clean up any borders.
        textarea.style.border = 'none';
        textarea.style.outline = 'none';
        textarea.style.boxShadow = 'none';

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

    existsTextarea.value = text;
    existsTextarea.select();

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

Play with the following fiddle:

2. Using Clipboard.js

Everybody loves libraries, you should love libraries. A library makes everything easier for you and it has been tested for many people. Clipboard.js is one of those beautiful libraries that with a couple of lines will help you to achieve your goal. Clipboard.js is a modern approach to copy text to clipboard without Flash, it has no dependencies and is lightweight.

To initialize clipboard.js, use the following code:

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

<script>
var clipboard = new Clipboard('.btn');

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

    e.clearSelection();
});

clipboard.on('error', function(e) {
    console.error('Accion:', e.action);
    console.error('Trigger:', e.trigger);
});
</script>

Clipboard constructor expects a dom selector as first parameter. In this case all the items with class btn will copy text into the clipboard. This library relies too on execCommand.

Fallback with flash

If you really need to implement this feature on your website and give support to old browsers you'll not have another option than provide a fallback using flash.

But don't worry about making a mess on your code, you can implement a clean solution using ZeroClipboard. See a working demo visiting the homepage of the plugin here.

However, this solution is neither free of limitations. Due to browser and Flash security restrictions, this clipboard injection can only occur when the user clicks on the invisible Flash movie. A simulated click event from JavaScript will not suffice as this would enable clipboard poisoning.

The implementation of ZeroClipboard is so easy as :

<!DOCTYPE html>
<html>
 <head>
 <!-- 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>
 </head>
 <body>
 <button id="copy-button" data-clipboard-text="Copy Me!" title="Click to copy me.">Copy to Clipboard</button>
 <script>
    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`
           // `event.target` === the element that was clicked
           event.target.style.display = "none";
           alert("Copied text to clipboard: " + event.data["text/plain"] );
        });
    });
 </script>
 </body>
</html>

Have fun !


Senior Software Engineer at Software Medico. Interested in programming since he was 14 years old, Carlos is a self-taught programmer and founder and author of most of the articles at Our Code World.

Sponsors