In the past, using JavaScript to copy and paste text through the clipboard was very cumbersome. While developing NTUST.ME, a short URL service for National Taiwan University of Science and Technology, I wanted to make it easy for people to copy the shortened URLs, so I looked into the clipboard API in JavaScript. I found that newer browsers have an execCommand function that supports many handy text operations, such as copy and select all. Let me introduce it to you!

I suspect that for security reasons, you currently can’t read text from the clipboard (that is, the paste function). You can only put data into the clipboard (copy).

Browser Compatibility

FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
copy/cut43?41 (41)92910

Sample Code

// Native JS Version
function copy(s) {
  var clip_area = document.createElement('textarea');
  clip_area.textContent = s;

document.body.appendChild(clip_area); clip_area.select();

document.execCommand(‘copy’); clip_area.remove(); }

//jQuery Version
function copy(s) {
  $('body').append('<textarea id="clip_area"></textarea>');

var clip_area = $(’#clip_area’);

clip_area.text(s); clip_area.select();

document.execCommand(‘copy’);

clip_area.remove(); }

Explanation

document.execCommand is a text editing API provided by the browser. Besides the copy operation used here, it can also apply bold, italic, hyperlinks, and other formatting inside a Textarea.

The approach here is to create a Textarea element, put the text you want to copy into it, and select all of it. Then run document.execCommand(‘copy’) to copy the text, and finally remove the Textarea element. Because this happens very quickly, you hardly notice the Textarea exists. Note that you must not hide the Textarea, or the text won’t be copied!

References