WebTuts - seomat.com

Your ultimate destination for comprehensive, easy-to-follow web tutorials.

Copy content to the clipboard in JavaScript

The navigator.clipboard API is a feature in JavaScript that provides the ability to read from and write to the system clipboard.

The navigator.clipboard interface is part of the Clipboard API, which provides an easy way to read from and write to the system clipboard. This API allows web applications to access the clipboard (cut, copy, and paste operations) and interact with clipboard data.

The navigator.clipboard interface provides two primary methods:

  1. readText(): This method reads the current content of the clipboard as plain text.
  2. writeText(): This method writes the specified text to the clipboard.

Both methods return a promise, which allows you to handle success and error cases accordingly.

It's important to note that most modern browsers require user permission to interact with the clipboard. Typically, the permission is granted only in response to a user action, such as a click event. This measure ensures that the user has full control over their clipboard data and prevents potentially malicious websites from accessing sensitive information.

While using the navigator.clipboard API, it's crucial to provide a clear and intuitive user experience, indicating when the content has been successfully copied or informing the user if any errors occur during the process.

To illustrate how the Clipboard API can be used I created a simple function that uses the writeText() method to copy some text to the clipboard. For better UI, I used Bootstrap 5 and bootstrap-show-toast.

const copyTextToClipboard = (text, message) => {
    navigator.clipboard.writeText(text)
    .then(() => {
        bootstrap.showToast({
            header: "Information",
            body: message ? message : 'Copied to clipboard !',
            toastClass: "text-bg-success",
            delay: 1000
        });
    })
    .catch(err => {
        bootstrap.showToast({
            header: "Information",
            body: "Error during copy command.",
            toastClass: "text-bg-danger"
        });
    });
}

Demo:

See the Pen Copy content to the clipboard in JavaScript by Stanescu Eduard-Dan (@ZsharE) on CodePen.