How to copy to clipboard in Chrome extension

person sticking a post it on a white board with the words how to written on it

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;
				document.body.appendChild(copyDiv);
				copyDiv.innerHTML = text;
				copyDiv.unselectable = "off";
				copyDiv.focus();
				document.execCommand('SelectAll');
				document.execCommand("Copy", false, null);
				document.body.removeChild(copyDiv);
			}

You May Also Like

6 Comments

    1. 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. 

      1. 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 *

This site uses Akismet to reduce spam. Learn how your comment data is processed.