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.
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.
Suppose we want to copy the text entered by the user in an input element to the clipboard.
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.