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.

Javascript

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.

Important

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

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

Use the following fiddle to play:

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

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

  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>

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