Also available in: Français

You certainly already met those buttons to “Copy into Clipboard”. They usually use a trick made with Flash to overcome a security feature provided by our web browsers? Avec the evolution of JS API and the listening of developer requests, you can now (since some months) do it with JavaScript natively.

The technic is quite simple. You just need to use the execCommand() function available at the document level.

What is execCommand()

The execCommand() function looks like that:

document.execCommand( commandName, showDefaultUI, valueArgument );

where the parameters are:

  • commandName:
    the command name to execute (copy, paste, undo, redo, insertHTML, etc.)
  • showDefaultUI:
    true or false, to use the default interface (or not… not supported bu Mozilla at the moment)
  • valueArgument:
    some commands need an argument, for example the insertImage command which is waiting for an URL as value.

As its name tells us, it provide to you the ability to execute a command inside the current window. To get a better and complete documentation the MDN article is a good resource.

Code snippet

To give you the essential point of this feature, I will write a minimalist code example. I’ll let you click on the demo link below (which presents a code too) if you want a more concret how-to-use example.

Let’s imagine this HTML:

<textarea id="to-copy">
Write something and copy it into your clipboard by clicking in the button below.
</textarea>
<button id="copy" type="button">
Copy in Clipboard
</button>

The next JavaScript code is very simple and provides you the main “copy in your clipboard” function. The content of the textarea element will be copied on a simple button click. Then, you can paste this content where ever you want. (other input field, editing document, etc.)

var toCopy = document.getElementById( 'to-copy' ),
btnCopy = document.getElementById( 'copy' );

btnCopy.addEventListener( 'click', function(){
toCopy.select();
document.execCommand( 'copy' );
return false;
} );

When document.execCommand() succeeded it returns true, at the opposite if something went wrong (no support or error) it returns false.
I let you imagine what you can do with that. By the way, take a look at this example:

Demo on CodePen

Share your code on CodePen and in a new comment in that blog to show your results, I’m curious 🙂

The Clipboard.js micro librairy can help you to improve developement possibilities. Take a look at Clipboard.js

Have fun!