Categories
JavaScript Answers

How to add paste image from clipboard functionality with JavaScript?

Spread the love

Sometimes, we want to add paste image from clipboard functionality with JavaScript.

In this article, we’ll look at how to add paste image from clipboard functionality with JavaScript.

How to add paste image from clipboard functionality with JavaScript?

To add paste image from clipboard functionality with JavaScript, we can listen to the document paste event and get the image from the paste event handler.

For instance, we write

document.onpaste = (event) => {
  const items = (event.clipboardData || event.originalEvent.clipboardData)
    .items;
  console.log(JSON.stringify(items));
  let blob = null;
  for (let i = 0; i < items.length; i++) {
    if (items[i].type.indexOf("image") === 0) {
      blob = items[i].getAsFile();
    }
  }

  if (blob !== null) {
    const reader = new FileReader();
    reader.onload = (event) =>{
      console.log(event.target.result); 
    };
    reader.readAsDataURL(blob);
  }
};

to set document.onpaste function to a function that gets the image data.

In it, we get the clipboard data with

const items = (event.clipboardData || event.originalEvent.clipboardData)
    .items;

Then we create the blob with a for loop that gets the item from the items array with type having the substring 'image' in it.

Then we use the FileReader object’s readAsDataURL to read the blob as a base64 image URL string.

And we get the image data with event.target.result in reader.onload.

Conclusion

To add paste image from clipboard functionality with JavaScript, we can listen to the document paste event and get the image from the paste event handler.

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 *