"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How Does Pasting Images from Clipboard Work in Gmail\'s Chrome 12+ Update?

How Does Pasting Images from Clipboard Work in Gmail\'s Chrome 12+ Update?

Published on 2024-11-08
Browse:601

How Does Pasting Images from Clipboard Work in Gmail\'s Chrome 12  Update?

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.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3