JavaScript Copy to ClipBoard (without Flash) using Cut and Copy Commands with document.execCommand()

Using the cut and copy commands via document.execCommand(), a text selection can be cut or copied to the user’s clipboard in Chrome 43+, Opera 29+ and IE 10+. This means we can now cater to a part of our web userbase with the copy to clipboard feature without using Flash. Let’s write some code to see these commands in action.

Here’s a simple HTML representing an input field with a button to copy the contents of the field.

What's the one thing every developer wants? More screens! Enhance your coding experience with an external monitor to increase screen real estate.

<input id="url_field" type="url" value="">
<input id="copy_btn" type="button" value="copy">

and here’s the JavaScript magic:

var copyBtn = document.querySelector('#copy_btn');
copyBtn.addEventListener('click', function () {
  var urlField = document.querySelector('#url_field');
  // select the contents;
  document.execCommand('copy'); // or 'cut'
}, false);

Supporting Firefox will require a preference change, check out the cut and copy commands here. Since your users won’t probably have those preferences changed, feel free to wrap document.execCommand('copy') in a try/catch block to prevent Firefox from throwing errors.

The example we just covered shows how the text of an input field or a textarea can be selected and eventually copied. But what if the text to copy is not a part of a form field but a general span or p (or some other HTML) tag. In that case we can use the Selection API to make a selection and then execute the copy command. Let’s change our HTML:

<span id="url_field"></span>
<input id="copy_btn" type="button" value="copy">

and here goes the JS again:

var copyBtn = document.querySelector('#copy_btn');
copyBtn.addEventListener('click', function () {
  var urlField = document.querySelector('#url_field');
  // create a Range object
  var range = document.createRange();  
  // set the Node to select the "range"
  // add the Range to the set of window selections
  // execute 'copy', can't 'cut' in this case
}, false);

So we created a Range object using the document.createRange() method and selected our urlField. Then using the window.getSelection() method of the Selection API we added the “range” of selection (which is the entire URL selection) to our existing set of user selection ranges. Finally, since the text (url) is selected, executing the copy command via document.execCommand() copies the text to clipboard.

Make sure to call document.queryCommandSupported() before document.execCommand() to check whether a particular editor query command (copy and cut in this case) is supported by the browser or not. You could possibly disable the copyBtn based on the value (true or false) returned by document.queryCommandSupported().

This approach of executing copy/cut commands might seem a little dirty or hacky also because of the need to select the piece of text (programatically) first which has to be copied or cut. The HTML5 Clipboard API when properly implemented by all the browsers will solve this problem. With the Clipboard API we’ll have to write something like this (which is much simpler and elegant):

var copyEvent = new ClipboardEvent('copy', { dataType: 'text/plain', data: 'My string' } );

This way we can read whatever text from whichever element we want using JS and pass as data to the object argument.

Hope that helps!

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download

Author: Rishabh

Rishabh is a full stack web and mobile developer from India. Follow me on Twitter.

3 thoughts on “JavaScript Copy to ClipBoard (without Flash) using Cut and Copy Commands with document.execCommand()”

  1. The example is not good enough.
    I keep getting this error “Discontiguous selection is not supported” and the copy fails.

    After putting “window.getSelection().removeAllRanges();” inside the function, the error stopped.
    I’ve only tested this in Google Chrome.

  2. can we select and copy the html table (whole table with borders and style, not just the text) into the clipboard using the execCommand?

    1. You can try it, the result will be similar to a manual select + copy. For instance try this example, once copied, paste in google docs (or some other place that generally preserves styles like Gmail or MS Word).

      Note: Behaviour may vary across different browsers.

Leave a Reply

Your email address will not be published. Required fields are marked *