How does the paste image from clipboard functionality work in Gmail and Google Chrome 12+?
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:
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
withgetAsFile()
.
Handling and using image blobs
After unlocking the image Blob, two main paths lie ahead:
- Display: Convert the Blob to a Data URL through
FileReader.readAsDataURL()
. Now, this URL can illuminate animg
tag. - Upload: Use XMLHttpRequest with
FormData
to send this Blob on a journey to the server.
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 withFileReader.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.
Was this article helpful?