How to Copy Text to the Clipboard in JavaScript

Introduction

Copying text to the clipboard is a common functionality that developers often need to implement in web applications. Whether it's for sharing content or providing an easy way for users to copy information, being able to copy text to the clipboard is a valuable feature. In this article, we will explore various methods to copy text to the clipboard using JavaScript.

1. Document.execCommand() Method

One of the simplest ways to copy text to the clipboard is by using the `document.execCommand()` method. This method allows us to execute a specified command on the current document, such as copying text.


                const copyToClipboard = text => {
                    const textarea = document.createElement('textarea');
                    textarea.value = text;
                    document.body.appendChild(textarea);
                    textarea.select();
                    document.execCommand('copy');
                    document.body.removeChild(textarea);
                };
            

In the above code snippet, we create a textarea element, set its value to the desired text, append it to the document body, select the text within the textarea, execute the `copy` command, and then remove the textarea element from the document.

2. Clipboard API

In modern browsers, we can leverage the Clipboard API to interact with the clipboard directly. This API provides a more powerful and flexible way to copy text to the clipboard.


                const copyToClipboard = text => {
                    navigator.clipboard.writeText(text)
                        .then(() => {
                            console.log('Text copied to clipboard');
                        })
                        .catch(error => {
                            console.error('Error copying text to clipboard:', error);
                        });
                };
            

In the above code snippet, we use the `navigator.clipboard.writeText()` method to write the specified text to the clipboard. This method returns a Promise, allowing us to handle success and error cases accordingly.

3. Third-Party Libraries

If you prefer to use a third-party library to handle clipboard functionality, there are several options available. These libraries often provide additional features and cross-browser compatibility.

4. Browser Support

It's important to consider the browser support when implementing clipboard functionality. While the `document.execCommand()` method is supported in most modern browsers, the Clipboard API has limited support at the moment.

Here is the browser support for the Clipboard API as of October 2021:

  • Chrome: 66+
  • Firefox: 63+
  • Safari: Not supported
  • Edge: 79+
  • Opera: 53+

5. Conclusion

Copying text to the clipboard in JavaScript can be achieved using various methods. The `document.execCommand()` method and the Clipboard API are two common approaches. It's important to consider browser support and choose the method that best suits your needs.

Using the `document.execCommand()` method provides a simple way to copy text, but the Clipboard API offers more functionality and works better in modern browsers. Additionally, third-party libraries can be used to handle clipboard functionality with added features and cross-browser compatibility.