Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 24 You must be signed in to star a gist
  • Fork 8 You must be signed in to fork a gist
  • Save joeperrin-gists/8814825 to your computer and use it in GitHub Desktop.
Save joeperrin-gists/8814825 to your computer and use it in GitHub Desktop.
Copy To Clipboard in Google Chrome Extensions using Javascript. Source: http://www.pakzilla.com/2012/03/20/how-to-copy-to-clipboard-in-chrome-extension/
function copyToClipboard( text ){
var copyDiv = document.createElement('div');
copyDiv.contentEditable = true;
document.body.appendChild(copyDiv);
copyDiv.innerHTML = text;
copyDiv.unselectable = "off";
copyDiv.focus();
document.execCommand('SelectAll');
document.execCommand("Copy", false, null);
document.body.removeChild(copyDiv);
@dannyid
Copy link

dannyid commented Sep 25, 2015

Hey, I think I have an even cleaner version of this, which a) uses an input instead of a div, and b) keeps the element invisible on the page:

function copyToClipboard(text) {
  const input = document.createElement('input');
  input.style.position = 'fixed';
  input.style.opacity = 0;
  input.value = text;
  document.body.appendChild(input);
  input.select();
  document.execCommand('Copy');
  document.body.removeChild(input);
};

@misfo
Copy link

misfo commented Dec 2, 2015

Thanks, @dannyid . The input.style.position = 'fixed' "fixed" (punny, I know) an issue I had that would cause the browser to scroll.

Only thing I had to change was to use a textarea instead of an input in order to preserve line breaks...

@yairEO
Copy link

yairEO commented Jun 23, 2016

doesn't work.. FF 48

@f0r3v3ran00b
Copy link

Thanks all!

@m0o0scar
Copy link

Does the same technique works for copy image into clipbard?

@nameldk
Copy link

nameldk commented Jul 11, 2018

@dannyid const input = document.createElement('textarea'); It's would be better. The textarea will keep the raw format and the input will lose format.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment