Tuesday, 2 October 2018

Acting when the user pastes an image

I recently saw a question about how to act when someone paste's an image (from clipboard data). There is a plugin that can handle that - to store the image into a table, but I was interested from a purely academic perspective how this would work without using the plugin.

So, taking a look on MDN, I can see that there is a 'paste' event that you can listen to. See the documentation here: https://developer.mozilla.org/en-US/docs/Web/Events/paste.

Ok, so lets give this a whirl! I'm not going to cover loading this into a table/BLOB column, as it's been covered before. What we'll do, is create a region with an image element this will show our image as we paste - this can easily be extended to load it into a canvas, load into a table, whatever your hearts content!

Firstly, the region to show what the user pastes:

Next, we need a dynamic action. This will be a custom event ("paste") with the selector being the body.

Our True Action will be "Execute JavaScript Code" with code resembling:

function setImage(evt){
    var dataUrl = evt.target.result;
    $('#imageMagick').attr('src', dataUrl);

var pasteEvt = this.browserEvent;
var pasteItems =
    (pasteEvt.clipboardData || pasteEvt.originalEvent.clipboardData).items;

for (index in pasteItems){
    var item = pasteItems[index];
    if (item.kind === "file"){
        var pasteBlob = item.getAsFile();
        if (pasteBlob.type === "image/png"){
            var reader = new FileReader();
            reader.onload = setImage;

Now, when you paste, the image will get loaded into the region, with the img placeholder we set up. Neat! You may wish to cancel event propagation, but I'll leave that up to you to experiment with depending on your needs.

If you want to try out this specific example, I have an example:  https://apex.oracle.com/pls/apex/f?p=14882:32

Sources used in the making of this example:

- https://developer.mozilla.org/en-US/docs/Web/Events/paste
- https://stackoverflow.com/questions/6333814/how-does-the-paste-image-from-clipboard-functionality-work-in-gmail-and-google-c