Pasting Images from Clipboard into Gmail: How It's Done in Chrome 12
Google's announcement of the ability to paste images directly from the clipboard into Gmail using Chrome 12 has sparked curiosity about the underlying mechanism. Despite using the latest Chrome version, some users have been unable to find information on how this enhancement was implemented in Webkit.
Upon experimentation, it appears that Chrome has adopted the emerging Clipboard API specification. This specification enables the definition of a "paste" event handler that can access the event.clipboardData.items property. By calling getAsFile() on each item, a Blob object can be obtained. FileReader can then be used on this Blob to determine its contents.
Below is a code snippet demonstrating how to obtain a data URL for a pasted image:
document.onpaste = function (event) { var items = (event.clipboardData || event.originalEvent.clipboardData).items; for (var index in items) { var item = items[index]; if (item.kind === 'file') { var blob = item.getAsFile(); var reader = new FileReader(); reader.onload = function (event) { console.log(event.target.result); // data URL! }; reader.readAsDataURL(blob); } } };
Once a data URL is available, the image can be displayed. Alternatively, it can be uploaded using FormData or readAsBinaryString.
It's important to note that while JSON.stringify may not work on the items list directly, MIME types can be obtained by iterating through each item using the DataTransferItem data structure.
The above is the detailed content of How Does Pasting Images from Clipboard Work in Gmail\'s Chrome 12 Update?. For more information, please follow other related articles on the PHP Chinese website!