Copy to Clipboard in Chrome Extension

Solution 1:

All credit goes to joelpt, but in case anyone else needs this to work in pure javascript without jQuery (I did), here's an adaptation of his solution:

function copyTextToClipboard(text) {
  //Create a textbox field where we can insert text to. 
  var copyFrom = document.createElement("textarea");

  //Set the text content to be the text you wished to copy.
  copyFrom.textContent = text;

  //Append the textbox field into the body as a child. 
  //"execCommand()" only works when there exists selected text, and the text is inside 
  //document.body (meaning the text is part of a valid rendered HTML element).
  document.body.appendChild(copyFrom);

  //Select all the text!
  copyFrom.select();

  //Execute command
  document.execCommand('copy');

  //(Optional) De-select the text using blur(). 
  copyFrom.blur();

  //Remove the textbox field from the document.body, so no other JavaScript nor 
  //other elements can get access to this.
  document.body.removeChild(copyFrom);
}

Solution 2:

I found that the following works best, as it lets you specify the MIME type of the copied data:

copy: function(str, mimeType) {
  document.oncopy = function(event) {
    event.clipboardData.setData(mimeType, str);
    event.preventDefault();
  };
  document.execCommand("copy", false, null);
}

Solution 3:

I'm using this simple function to copy any given plaintext to the clipboard (Chrome only, uses jQuery):

// Copy provided text to the clipboard.
function copyTextToClipboard(text) {
    var copyFrom = $('<textarea/>');
    copyFrom.text(text);
    $('body').append(copyFrom);
    copyFrom.select();
    document.execCommand('copy');
    copyFrom.remove();
}

// Usage example
copyTextToClipboard('This text will be copied to the clipboard.');

Due to the fast append-select-copy-remove sequence, it doesn't seem to be necessary to hide the textarea or give it any particular CSS/attributes. At least on my machine, Chrome doesn't even render it to screen before it's removed, even with very large chunks of text.

Note that this will only work within a Chrome extension/app. If you're using a v2 manifest.json you should declare the 'clipboardWrite' permission there; this is mandatory for apps and recommended for extensions.

Solution 4:

The Clipboard API is now supported by Chrome, and is designed to replace document.execCommand.

From MDN:

navigator.clipboard.writeText(text).then(() => {
    //clipboard successfully set
}, () => {
    //clipboard write failed, use fallback
});