Categories
JavaScript Answers

How to Copy Text to a Clipboard Programmatically in JavaScript?

Spread the love

Copying text to the system clipboard programmatically is something that we may have to do sometimes.

We can do this with plain JavaScript code in web apps.

In this article, we’ll look at how to copy text to a clipboard in JavaScript programmatically.

The Old Way

The old way is to create a text area, put the text we want to copy to it, then call document.execCommand to run the copy command to copy the text to the clipboard.

For instance, we can write:

const text = 'hello world'
const textArea = document.createElement("textarea");
textArea.value = text;
textArea.style.top = "0";
textArea.style.left = "0";
textArea.style.position = "fixed";

document.body.appendChild(textArea);
textArea.focus();
textArea.select();

try {
  const successful = document.execCommand('copy');
  const msg = successful ? 'successful' : 'unsuccessful';
  console.log(msg);
} catch (err) {
  console.error(err);
}

document.body.removeChild(textArea);

The text variable has the text that we want to copy to the clipboard.

We then create the document.createElement method to create a textarea element.

Then we set the textArea ‘s value to text to put the text in the text area.

Next, we set the top , left and position styles to prevent scrolling to the bottom.

Then we call document.body.appendChild with textArea to add the text area to the body.

Next, we focus on the textArea with focus .

Then we call select to select the text in the text area so we can copy it.

Next, we call document.execCommand with 'copy' to issue the copy command to copy the text we selected in the text area.

It returns a boolean to indicate whether the command was successfully run.

Then we can paste the text anywhere we want.

The New Way

The new way of copying text programmatically to the clipboard with JavaScript is a lot cleaner.

We just call the navigator.clipboard.writeText method with the text we want to copy as the argument to copy the text programmatically to the clipboard.

To do it, we write:

const text = "abc";
(async () => {
  await navigator.clipboard.writeText(text);
})();

We just call navigator.clipboard.writeText with text to copy the text.

It returns a promise with the copy status so we can put it in an async function.

This is supported in newer browsers.

Conclusion

There are various ways to copy data to the clipboard programmatically with JavaScript.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *