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);
Related Posts Plugin for WordPress, Blogger...

6 thoughts on “How to copy to clipboard in Chrome extension

      • 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

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

Leave a Reply

Your email address will not be published. Required fields are marked *