How to copy to clipboard in Chrome extension

While developing a Chrome extension you can come up with the situation to copy text to clipboard. I was searching over internet since I found following code snippet. It works like a charm.

function copyToClipboard( text ){
			  	var copyDiv = document.createElement('div');
				copyDiv.contentEditable = true;
				copyDiv.innerHTML = text;
				copyDiv.unselectable = "off";
				document.execCommand("Copy", false, null);
  • Ozlig_wow

    dont work in chrome

    • I have verified the code. It’s working in my unpackaged extension. My version of Google Chrome is 19.0.1084.52 m. May be you were missing some thing. 

      • Dont forget to add the permissions on the extension manifest.

        “clipboardRead”Required if the extension uses document.execCommand(‘paste’).”clipboardWrite”Indicates the app or extension uses document.execCommand(‘copy’) or document.execCommand(‘cut’). This permission is required for hosted apps; it’s recommended for extensions and packaged apps

  • Ozlig_wow

    may be works, but not in Chrome

  • Razon

    yes, here its works my chrome version 19.06++++

  • Josh

    Ive literally been searching for this for 2 weeks, finding similar code to this which doesnt work. This works. Thank you!