Categories
JavaScript Answers

How to paste an image from clipboard using JavaScript?

Spread the love

Sometimes, we want to paste an image from clipboard using JavaScript.

In this article, we’ll look at how to paste an image from clipboard using JavaScript.

How to paste an image from clipboard using JavaScript?

To paste an image from clipboard using JavaScript, we can listen to the document‘s paste event.

For instance, we write

document.onpaste = (event) => {
  const items = (event.clipboardData ?? event.originalEvent.clipboardData)
    .items;
  for (const item of items) {
    if (item.kind === "file") {
      const blob = item.getAsFile();
      const reader = new FileReader();
      reader.onload = (event) => {
        console.log(event.target.result);
      };
      reader.readAsDataURL(blob);
    }
  }
};

to set document.onpaste to a function that runs when we paste something onto the page.

In it, we get the pasted items from event.clipboardData or event.originalEvent.clipboardData.

Then we use a for-of loop to loop through the items.

In it, we check if item.kind is a 'file'.

If it is, we call item.getAsFile to get the pasted item as a blob.

And we use the FileReader instance’s onload method get the read file.

The read file’s content is in event.target.result.

It’s a base64 string since we read it with readAsDataURL.

Conclusion

To paste an image from clipboard using JavaScript, we can listen to the document‘s paste event.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *