Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Copy To Clipboard in Google Chrome Extensions using Javascript. Source:
function copyToClipboard( text ){
var copyDiv = document.createElement('div');
copyDiv.contentEditable = true;
copyDiv.innerHTML = text;
copyDiv.unselectable = "off";
document.execCommand("Copy", false, null);
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'); = 'fixed'; = 0;
  input.value = text;

Copy link

misfo commented Dec 2, 2015

Thanks, @dannyid . The = '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...

Copy link

yairEO commented Jun 23, 2016

doesn't work.. FF 48

Copy link

f0r3v3ran00b commented Nov 16, 2017

Thanks all!

Copy link

m0o0scar commented Dec 22, 2017

Does the same technique works for copy image into clipbard?

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