JavaScript/Clipboard

Text can be copied to the clipboard in JavaScript using the navigator.clipboard.writeText method. However, to prevent unsolicited copying to clipboard, web browsers only allow it in response to a click or tap by the user.

In the following demonstration, a time stamp is generated, inserted into the text area, and then copied to the clipboard.

Source code

edit
<!DOCTYPE html>
<html>
<head>
	<title>Copying text to the clipboard in JavaScript</title>
	<meta name="author" content="Elominius from Wikiversity">

	<!-- the viewport meta tag magnifies the page on mobile browsers to make it useable there -->
	<meta name="viewport" content="initial-scale=1.0, user-scalable=yes">

	<style type="text/css">
		/* modern font pack and dark theme */
		body { 
			font-family: ubuntu,'noto sans','open sans', calibri, 'segoe ui', 'trebuchet ms', arial, helvetica, verdana, tahoma, 'Bitstream Vera Sans', 'sans-serif';
			color: #ccc;
			background-color: #222;
		}
	</style>
</head>

<body>

<p>Click on the button to generate a time stamp and copy the text from the text field. Try to paste the text afterwards in a different window using <kbd>Ctrl</kbd>+<kbd>V</kbd> on desktop or the clipboard menu on mobile devices, to see the effect.</p>

<input type="text" value="" id="input_field">
<button onclick="copy_to_clipboard();">Copy to clipboard</button>

<script>
// set variable that refers to the input field
var input_field = document.getElementById("input_field");
function generate_time_stamp() {
  // fills the text area with time stamp; replacing colons with dashes to make it useable for file naming, since some operating systems like Windows do not support colons in file names.
  // The replace() method isused twice instead of replaceAll() for browser compatibility.	
	return (new Date).toISOString().replace(":","-").replace(":","-");
}

  // pre-fill field
  input_field.value=generate_time_stamp();

function copy_to_clipboard() {

  input_field.value=generate_time_stamp();

  // select the text in the field
  input_field.select();
  input_field.setSelectionRange(0, 99999); // might be necessary on some mobile web browsers

  // copy the text from the text box to the clipboard
  navigator.clipboard.writeText(input_field.value);

  // alert the copied text for confirmation
  alert("Copied to clipboard: " + input_field.value);
}
</script>

</body>
</html>