Hi, In this blog post, we will create a JS function that can copy text from a text field into clipboard and can also paste text and images from the clipboard on the webpage. This is basic functionality that is used by almost every content website. So, you need to know how it works.

HTML Elements for Project

Let's create some HTML elements, where we will perform copy-paste functionality. First, we need an input field, it may be textarea or some editable div's. And further, we need two buttons, one for executing copy function, and another one for the paste function. In addition, we also need a content element, where we can show the paste content. It may be a div or anything you want to use.

Copy Function

Copy function is simple as compared to the paste function. In copy function, you just need to pass the content to write in your clipboard. In this application, we are getting content from a div using innerHTML and store in a variable. Now pass the variable to the writeText method of the clipboard object. This will write all your content including emojis, symbols, and characters on your clipboard and you can use it anywhere.

Paste Function

Paste is an async function and we can read data from the clipboard using read method of the clipboard object. Read method uses await keyword so that it waits until it gets its value. All the clipboard content will store in a data variable. As the response content is an array, so get the first index of the array to get our useful content. It may have plain text or images along with its type. Also, get the type using types[0] as we need in this application. Now, we have both content and its type. Let's decide on the base of type that content is text or image as to paste both types of data, we need different codes.

For Paste Text

Now get all text type data from the available content using getType('text/plain'). It returns a blob. Convert blob to text using the text() method. Now we have text and just want to display it on the webpage. Create a paragraph tag, add the text to that tag and append it to the paste element as given below.

For Paste Image

Get all image data using getType('image/png'). Its returns a blob. Convert blob into URL using createObjectURL method. This will create an object URL of the image. Now use the URL as you want, and here we just want to show the image on the webpage. Create an image tag, provide the URL to the image tag as src and append it to the paste element as given below.

Final Thoughts

I hope you understand, how to use the clipboard to store and transfer data from one to another place within an application or even outside in javascript. Now you can easily add this feature to your projects if there is a need. Get the source code below and if you want to give some suggestion then comment below.