Friday, September 17, 2010

Copy to Clipboard in HTML/JavaScript and Chrome Extension

When you develop a Google Chrome Extension you probably faces the problem of missing the clipboard interaction API available in Chrome browser. That's true, as of September 2010 and Chrome version
6.0 there is no Clipboard API in Google Chrome browser.

Google is experimenting on that in Development builds of Chrome browser and the Experimental Clipboard API is available to test only in these builds. It makes it impossible to use in production.

But the answer comes from the remembering that Chrome Extension is a plain HTML and JavaScript where the regular DOM and BOM structures are available.

Copying text to Clipboard in HTML/JavaScript requires three simple steps:
  1. Put text to the input element
  2. Focus on that element and select all text you need to copy
  3. Execute DOM's "Copy" command that gets the current selection and puts to the clipboard automatically
In JavaScript such function could look like this:
// Copy text to the Clipboard function
// uses 'url' input element to select text
// parameters: text - text to be copied to the clipboard
function copyToClipboard( text )
  var input = document.getElementById( 'url' );
  input.value = text;
  document.execCommand( 'Copy' );


  1. sposibo, but unfortunately this does not seem to work : / ( i put your code in my popup.html and added a textarea which was called 'url')

  2. AWESOME !
    It's works . thank you

  3. It doesnt work at Chrome!

  4. Leonid,
    Please clarify if you have ever seen this work on Chrome.
    It does not work on Chrome for me.
    Tested on 27-Jul-2012. Using Windows 7 64 bits and Chrome 20.0.1132.57

  5. make it at the mouseup event becaus the mouse up event remove the selection

  6. It doesn't work in content script. It works in popup extension, but not when I've tried to modify some pages...

  7. Chrome doesn't do document.execCommand('copy') since October 2010. This article only had a life of 2 weeks.