Explain Codes LogoExplain Codes Logo

How does the paste image from clipboard functionality work in Gmail and Google Chrome 12+?

javascript
clipboard-api
event-listener
web-development
Nikita BarsukovbyNikita Barsukov·Sep 20, 2024
TLDR

Injecting images directly into Gmail or Web Apps in Chrome is empowered by the Clipboard API and the availability of the paste event. This event listens to the action on an element and enables access to the contents of the clipboard, including images as Blob objects within DataTransfer items:

document.onpaste = function(event) { var items = event.clipboardData.items; for (var i = 0; i < items.length; i++) { if (items[i].type.indexOf('image') !== -1) { var blob = items[i].getAsFile(); // Next: Handle this image blob as if it's a star of your program } } };

This listener scrubs through the clipboard, checks for images (mime type validation), converts images to a Blob, and finally, it's your play.

Digging deep into event.clipboardData

Pasting images is no magic, and this magic's wand swirls around event.clipboardData. When a paste event is triggered, this wand sprinkles the dust, leading to the appearance of this object, which saves all pasted content into the document. To unveil images:

  • Validate each item's mime type with the type property.
  • Convert the image item to a file-like Blob with getAsFile().

Handling and using image blobs

After unlocking the image Blob, two main paths lie ahead:

  1. Display: Convert the Blob to a Data URL through FileReader.readAsDataURL(). Now, this URL can illuminate an img tag.
  2. Upload: Use XMLHttpRequest with FormData to send this Blob on a journey to the server.
function shoutOutToBlob(blob) { var formData = new FormData(); formData.append('file', blob, 'newbie.png'); // Name & fame var xhr = new XMLHttpRequest(); xhr.open('POST', '/upload', true); // Replace '/upload' with your server's upload spot xhr.onload = function() { if (this.status === 200) { // The blob has just started its celebrity life on the server! console.log('Upload finished! Applause!', this.responseText); } }; xhr.send(formData); }

Compatibility & fallback strategies

Life isn't entirely fair. Sometimes, it's the older browsers; other times, it's the cross-browser compatibility that puts stones in your way.

  • Older browsers: If they don't support event.clipboardData.items, pat their back and serve them with FileReader.readAsBinaryString.
  • IE below 10: Treat them with Flash-based solutions or nourish them with APIs like Adobe AIR.
  • Non-Chrome browsers:
    • Develop a solid fallback strategy; a file input field can quickly turn into a lifesaver here.

Following the footsteps of Webkit and Chrome

Chrome is known for its constant efforts in doing the new. All thanks to Webkit. Check out the Webkit updates or Chrome's release notes to discover the enhancements addressing clipboard events and data.

Coding recipes and the real-world application

Stuffing the cooked code in your baggage won't be enough!

  • Embed an onpaste event in your HTML to cue the pasty function.
  • Let JavaScript take it forward and mould it into an img or canvas element, ready to speak the language of UI.

Tips, tricks & common hurdles

Working with Clipboard API can sometimes send you on a roller coaster ride. Here are a few safety checks:

  • If there're multiple image types, make sure to handle each image's mime type correctly.
  • In newer Chrome versions, simplify your work: event.originalEvent.clipboardData.
  • Don't forget the cardinal rule: Test across different browsers and platforms.

Exploring other ways

What if you hit a roadblock with Clipboard API?

  • Be the boss, and tell Adobe AIR API how to handle clipboard access in desktop applications.
  • Bring in a signed Java applet as a knight in shining armour for cross-platform fallback.