Register Login

Copy Text to Clipboard using JavaScript

Updated Apr 06, 2023

The copy-and-paste feature in modern computing is one of the most commonly used techniques. Programmers can use JavaScript to allow end-users to copy and paste text or images from one section to the other.

It refers to the process of transferring or copying content. Today, programmers widely use this technique to programmatically copy their needed contents to the clipboard of an end-user without manually doing so. In this article, you will find three ways of copying content on the clipboard using JavaScript.

  1. Using the document.execCommand()
  2. Overriding the copy event
  3. Using the navigator.permissions and writeText() method

Method 1: Using the document.execCommand() method in JavaScript

To add content inside content’s editable container, programmers use this method in JavaScript. The document.execCommand() method is a valid editing method that executes the command and manipulates the content defined by the end-user on the editable selected section.

Syntax:

document.execCommand( command, showUI, value )

Parameters used:

Programmers, when applying this method, can use three parameters which are as follows:

  • Command: Using this parameter, programmers can specify the name of the command that the method will execute on the selected section. Some of these commands in HTML are backcolor, copy, bold, delete, cut, etc.
  • showUI: It helps programmers specify the Boolean value that indicates whether the UI showed.
  • Value: This parameter accepts the value of the given commands.

Code Snippet:

<html>
<head>
<meta charset="utf-8">
<title>Copy Text to Clipboard in JavaScript</title>
</head>

<body>
<h1 style = "color:maroon;">Copy Text to Clipboard in JavaScript</h1>
<input type = "text" value = "This is the default message"id = "demo">
<button onclick = "samp()">Copy the content</button>
<script>
	function samp() {
		var a = document.getElementById("demo");
		a.select();
		document.execCommand("copying");
		document.getElementById("sample").innerHTML = "The browser has copied the text: " + a.value;
	}
</script>
<p>Users, you click the "Copy text" button to copy the content from the text dialog box.<br>
	You can also use your keyboard and press and paste the text by pressing the keys: ctrl+v) afterward in a different window, to see the effect.</p>
<p id="sample"></p>
</body>
</html>

Output:

Run Code

Explanation:

In the above example, we used JavaScript and HTML to create a program using the document.execCommand() method that copies the content from one section to another when end-users trigger the action. The document.execCommand() will capture or copy the value.

Example 2:

<html>
<head>
<meta charset="utf-8">
<title>Copy Text to Clipboard in JavaScript</title>
</head>
<body>
<p>
  <button class = "js-contentcopybtn" style = "vertical-align:top;"> Copy the content</button>
  <textarea class = "js-copycontent"> The default message is this</textarea>
</p>
<script>
var a = document.querySelector('.js-contentcopybtn');

a.addEventListener('click', function(event) {
	var b = document.querySelector('.js-copycontent');
  	b.focus();
  	b.select();
	try {
    	var s = document.execCommand('copy');
    	var m = successful ? 'successful' : 'not successful';
    	console.log('Copying text command was ' + m);
		document.getElementById("sample").innerHTML = "The browser has copied the text: "
							+ a.value;
  	} catch (err) {
    	console.log('Sorry, the content cannot copied');
		document.getElementById("sample").innerHTML = "Sorry, the content cannot copied";
  }
});
</script>
	<p id="sample"></p>
</body>
</html>

Output:

Then used ctrl + v and paste the content to test whether the content is copied:

Run Code

Explanation:

In the above code snippet, we used the document.querySelector() method that copies the content after triggering the HTML button. The addEventListener() method returns the event handler to the HTML element without changing the current event handlers.

Method 2: Overriding the copy event

Code Snippet:

<html>
<head>
<meta charset="utf-8">
<title>Copy Text to Clipboard in JavaScript</title>
<script>
document.addEventListener('copy', function(clip) {
	var a = document.getElementById("demo2");
  	clip.clipboardData.setData('text/plain', a.value);
  	document.getElementById("demo").innerHTML = a.value;
  	clip.preventDefault();
});
</script>
</head>
<body>
<input type = "text" value = "This is the default text" id = "demo2">
<h3> Click on the dialog box and Press ctrl + c and you can see the browser copies the text and display it in the blank space </h3>
<p id = "demo"></p>
</body>
</html>

Output:

After pressing ctrl + c, it automatically paste the text or content

Run Code

Explanation:

In the above example, we used the document.addEventListener('copy', function() and initialized a parameter clip representing the data we want to copy. Then we used this parameter with the clipboardData property that specifies what data users want to put into the clipboard from the cut and copy event handlers, generally with a setData('text/plain', a.value) call.

Using the navigator.permissions and writeText() method

Code Snippet:

<html>
<head>
<meta charset="utf-8">
<title>Copy Text to Clipboard in JavaScript</title>
</head>
<body>
<p> Here, you can copy the text in the dialog box by clicking the given button and copying the text from the text field. You can also use your keyboard and press and paste the text by pressing the keys: ctrl+v.</p>
<input type = "text" value = "The default message" id = "demo">
<button onclick = "func()"> Click to copy </button>
<script>
function func() {
  var a = document.getElementById("demo");
  a.select();
  a.setSelectionRange(0, 99999);
  navigator.clipboard.writeText(a.value);
  alert("Here is the content that you typed: " + a.value);
}
</script>
</body>
</html>

Output:

Run Code

Explanation:

We just used the navigator.permissions and writeText() and generated an article where the end-user will see a dialog box showing a default message, "The default message." After clicking the copy button the method returns, and displays a pop-up message that it has copied the given content or text with the browser's permission.

Conclusion:

We hope this short guide has provided all the necessary information to JavaScript users who want to create a program that allows their end-users to copy the content on their clipboard. These are the two most widely used techniques, i.e., document.execCommand() method and navigator.permissions with writeText() method.


×