Traditionally developers used to depend on libraries to implement copy to clipboard features. Later they started achieving the same functionality using the execCommand method of the document object in the browsers. Now the execCommand is deprecated and the browsers are removing this feature slowly.

While discouraging the use of execCommand, browsers also introduced a new feature called Clipboard API. Using this new API, we can easily perform the tasks such as copying something to the clipboard or reading something from the clipboard.We will see how to copy the things to the clipboard.

How to Copy Text to the Clipboard in JavaScript

We can easily copy text to the clipboard by using the writeText method of the newly introduced object Clipboard which will be available on the navigator object.

example:

Suppose we want to copy the text entered by the user in an input element to the clipboard.

HTML:

Copy to Clipboard

JS:

Copy to Clipboard

How to Copy Image to the Clipboard in JavaScript

We can convert an image that we want to copy to clipboard into a blob then use the write method on the clipboard object. To convert the image to a blob, we can first draw the image to the canvas and covert that to a blob using the built-in toBlob method of the canvas.

example:

Copy to Clipboard