Copy text to clipboard using Javascript (Chrome)

From Is-beer-a-vegetable.com
Jump to: navigation, search

Copy text to clipboard using Javascript (Chrome)

For an application that I only use internally, I needed to be able to copy text (created programmatically) into the clipboard that I would them paste into another application.

Stack Overflow is full of articles purporting to be able to do, most of them howling about security, none of them worked using a current Chrome browser.

This works with Chrome Version 43.0.2357.81 (64-bit)

I am aware of the security implications but I trust myself not to attempt misuse. :-)

In my application the HTML / Javascript is dynamically created using perl.

I give you the code and leave it to you to worry about the security implications of using this on a public site - Googleing Stack Overflow will give you plent of reading.


Here's the code

<html>
		<body>
				<a href="#" onclick="executeCopy();">Click to copy</a>
				<script>
						function executeCopy(text) {
								var input = document.createElement('textarea');
								document.body.appendChild(input);
								input.value = ('Place text to be copied in here');
								input.focus();
								input.select();
								document.execCommand('Copy');
								input.remove();
						}
				</script>

		</body>
</html>