How to Copy Text from the Clipboard in JavaScript?

Estimated read time 2 min read

To copy text from the clipboard in JavaScript, you can use the clipboardData property of the event object, which is available in Internet Explorer, or the Clipboard API, which is available in modern browsers.

Here’s an example of how to copy text to the clipboard using the clipboardData property:

document.addEventListener("copy", function(event) {
  event.clipboardData.setData("text/plain", "Text to copy");
  event.preventDefault();
});

In this example, we add an event listener for the copy event to the document, and in the event handler, we use the setData method of the clipboardData property to set the text to be copied to the clipboard. We also call the preventDefault method to prevent the default behavior of the copy event.

Here’s an example of how to copy text to the clipboard using the Clipboard API:

navigator.clipboard.writeText("Text to copy").then(function() {
  console.log("Text copied to clipboard");
}, function(err) {
  console.error("Failed to copy text: ", err);
});

In this example, we use the writeText method of the Clipboard API to write the text to be copied to the clipboard. The method returns a Promise that resolves when the text has been successfully copied to the clipboard, or rejects if there was an error.

Please note that due to security and privacy concerns, the ability to copy text from the clipboard is typically restricted in web browsers. You may need to request permission from the user to copy text from the clipboard, and you should also provide a user interface, such as a button, to initiate the copy action.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply