15

Is it possible to simulate/fake the drop event using javascript only? How to test this type of event?

Take for example this dnd upload sample page , is it possible to trigger the "drop" event with a file without actually dropping a file there? Let's say clicking on a button?

I have started writing a Sukuli script that can control the mouse and do the trick but I was looking for a better solution.

EDIT

@kol answer is a good way to get rid of the drag and drop event but I still have to manually select a file from my computer. This is the bit I am interested in simulating. Is there a way to create a file variable programatically?

var fileInput = document.getElementById('fileInput'),
file = fileInput.files[0];    
caiocpricci2
  • 7,714
  • 10
  • 56
  • 88

2 Answers2

25

1. Dropping image selected by the user

I've made a jsfiddle. It's a stripped-down version of the html5demos.com page you've referred to, but:

  • I added an <input type="file"> tag which can be used to select an image file from the local computer, and
  • I also added an <input type="button"> tag with an onclick handler, which simulates the "drop file" event by directly calling the ondrop event handler of the DND-target div tag.

The ondrop handler looks like this:

holder.ondrop = function (e) {
    this.className = '';
    e.preventDefault();
    readfiles(e.dataTransfer.files);
}

That is, we have to pass an argument to ondrop, which

  • has a dataTransfer field with a files array subfield, which contains the selected File, and
  • has a preventDefault method (a function with no body will do).

So the onclick handler of the "Simulate drop" button is the following:

function simulateDrop() {
    var fileInput = document.getElementById('fileInput'),
        file = fileInput.files[0];        
    holder.ondrop({ 
        dataTransfer: { files: [ file ] }, 
        preventDefault: function () {} 
    });
}

Test

  1. Select an image file (png, jpeg, or gif)
  2. Click on the "Simulate drop" button

Result

Result

2. Dropping autogenerated test files without user interaction (GOOGLE CHROME ONLY!!!)

I've made another jsfiddle. When the page is loaded, a function gets called, which:

  • creates a text file into the temporary file system, and
  • loads and drops this text file into the target <div>; then
  • creates an image file into the temporary file system, and
  • loads and drops this image file into the target <div>.

The code of this drop-simulator function call is the following:

(function () {
    var fileErrorHandler = function (e) {
            var msg = "";
            switch (e.code) {
                case FileError.QUOTA_EXCEEDED_ERR:
                    msg = "QUOTA_EXCEEDED_ERR";
                    break;
                case FileError.NOT_FOUND_ERR:
                    msg = "NOT_FOUND_ERR";
                    break;
                case FileError.SECURITY_ERR:
                    msg = "SECURITY_ERR";
                    break;
                case FileError.INVALID_MODIFICATION_ERR:
                    msg = "INVALID_MODIFICATION_ERR";
                    break;
                case FileError.INVALID_STATE_ERR:
                    msg = "INVALID_STATE_ERR";
                    break;
                default:
                    msg = "Unknown Error";
                    break;
            };
            console.log("Error: " + msg);
        },
        requestFileSystem = window.requestFileSystem || window.webkitRequestFileSystem,
        dropFile = function (file) {
            holder.ondrop({ 
                dataTransfer: { files: [ file ] }, 
                preventDefault: function () {} 
            });
        };

    if (!requestFileSystem) {
        console.log("FileSystem API is not supported");
        return;
    }
    requestFileSystem(
        window.TEMPORARY, 
        1024 * 1024, 
        function (fileSystem) {
            var textFile = {
                    name: "test.txt",
                    content: "hello, world",
                    contentType: "text/plain"
                },
                imageFile = {
                    name: "test.png",
                    content: "iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==",
                    contentType: "image/png",
                    contentBytes: function () {
                        var byteCharacters = atob(this.content),
                            byteArrays = [], offset, sliceSize = 512, slice, byteNumbers, i, byteArray;

                        for (offset = 0; offset < byteCharacters.length; offset += sliceSize) {
                            slice = byteCharacters.slice(offset, offset + sliceSize);
                            byteNumbers = new Array(slice.length);
                            for (i = 0; i < slice.length; i++) {
                                byteNumbers[i] = slice.charCodeAt(i);
                            }
                            byteArray = new Uint8Array(byteNumbers);
                            byteArrays.push(byteArray);
                        }
                        return byteArrays;
                    }
                };

            // Create and drop text file
            fileSystem.root.getFile(
                textFile.name, 
                { create: true }, 
                function (fileEntry) {
                    fileEntry.createWriter(
                        function (fileWriter) {
                            fileWriter.onwriteend = function(e) {
                                console.log("Write completed (" + textFile.name + ")");
                                fileSystem.root.getFile(
                                    textFile.name, 
                                    {}, 
                                    function (fileEntry) {
                                        fileEntry.file(
                                            function (file) {
                                                dropFile(file);
                                            }, 
                                            fileErrorHandler
                                        );
                                    }, 
                                    fileErrorHandler
                                );    

                            };
                            fileWriter.onerror = function(e) {
                                console.log("Write failed (" + textFile.name + "): " + e.toString());
                            };
                            fileWriter.write(new Blob([ textFile.content ], { type: textFile.contentType }));
                        }, 
                        fileErrorHandler
                    );
                }, 
                fileErrorHandler
            );

            // Create and drop image file
            fileSystem.root.getFile(
                imageFile.name, 
                { create: true }, 
                function (fileEntry) {
                    fileEntry.createWriter(
                        function (fileWriter) {
                            fileWriter.onwriteend = function(e) {
                                console.log("Write completed (" + imageFile.name + ")");
                                fileSystem.root.getFile(
                                    imageFile.name, 
                                    {}, 
                                    function (fileEntry) {
                                        fileEntry.file(
                                            function (file) {
                                                dropFile(file);
                                            }, 
                                            fileErrorHandler
                                        );
                                    }, 
                                    fileErrorHandler
                                );    

                            };
                            fileWriter.onerror = function(e) {
                                console.log("Write failed (" + imageFile.name + "): " + e.toString());
                            };
                            fileWriter.write(new Blob(imageFile.contentBytes(), { type: imageFile.contentType }));
                        }, 
                        fileErrorHandler
                    );
                }, 
                fileErrorHandler
            );
        }, 
        fileErrorHandler
    );    
})();

The content of the auto-generated text file is given as a string, and the content of the image file is given as a base64-encoded string. These are easy to change. For example, the test text file can contain not just plain text, but HTML too. In this case, don't forget to change the textFile.contentType field from text/plain to text/html, and to add this content type to the acceptedTypes array and to the previewfile function. The test image can also be changed easily, you just need an image-to-base64 converter.

I had to extend the drop handler code to handle text files in addition to images:

acceptedTypes = {
    'text/plain': true, // <-- I added this
    'image/png': true,
    'image/jpeg': true,
    'image/gif': true
},

...

function previewfile(file) {
    if (tests.filereader === true && acceptedTypes[file.type] === true) {
        var reader = new FileReader();
        if (file.type === 'text/plain') { // <-- I added this branch
            reader.onload = function (event) {
                var p = document.createElement("p"); 
                p.innerText = event.target.result;
                holder.appendChild(p);
            }
            reader.readAsText(file);
        } else {
            reader.onload = function (event) {
                var image = new Image();
                image.src = event.target.result;
                image.width = 250; // a fake resize
                holder.appendChild(image);
            };
            reader.readAsDataURL(file);
        }
    } else {
        holder.innerHTML += '<p>Uploaded ' + file.name + ', ' + file.size + ' B, ' + file.type;
        console.log(file);
    }
}

Note that after loading the jsfiddle, the autogenerated files can be listed for debugging purposes:

Temporary file system

Result

Result

The screenshot shows that the simulated drop inserted the content of the autogenerated text file before the autogenerated image. The HTML code of the DND-target <div> looks like this:

<div id="holder" class="">
    <p>hello, world</p>
    <img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggkFBTzlUWEwwWTRPSHdBQUFBQkpSVTVFcmtKZ2dnPT0=" width="250">
</div>
kol
  • 27,881
  • 12
  • 83
  • 120
  • Thanks for the answer, I didn't know we could do that. That's not quite what i need but it should have been a part of my question. If we don't get another answer for the edit I'll give you the bounty! – caiocpricci2 Apr 02 '14 at 00:25
  • "That's not quite what i need" - What do you need *exactly*? This is not the only possible solution. For example, (1) the file chooser can be omitted if you drop an image which is generated dynamically, or which is already part of the page, or (2) the "simulate drop" button can be part of a browser extension. – kol Apr 02 '14 at 04:39
  • I need to remove the user interaction. Generate a "file" variable that takes another file from my system and can be "drag and dropped" in an element like in the sample fiddle. Not necessarily an image only, but if we can only do images it's already enough. – caiocpricci2 Apr 02 '14 at 13:20
  • As a last step would be good to know if there was a way to somehow pick a those files, either from the system or from a server. Thank you for your answer, that works for me. – caiocpricci2 Apr 03 '14 at 20:32
  • Hi there @kol I am trying to do similar but in Twitter "New Tweet" field. May you please check out this topic - http://stackoverflow.com/questions/37826583/bookmarklet-to-trigger-attach-of-mp4-to-tweet - i dont show in that topic but the drag and drop code i tried is this - https://github.com/Noitidart/Screencastify/blob/04e9990aaa8d9704d9ff0e2a82ab0f952d00402c/resources/scripts/MainFramescript.js#L333-L358 – Noitidart Jun 15 '16 at 06:30
  • Link to "image-to-base64 converter" in answer is dead. – Pang May 28 '18 at 06:19
4

@kol answer is a good way to get rid of the drag and drop event but I still have to manually select a file from my computer. This is the bit I am interested in simulating. Is there a way to create a file variable programatically? -caiocpricci2

Try this

function createFile() {
  var create = ["<!doctype html><div>file</div>"];
  var blob = new Blob([create], {"type" : "text/html"});
  return ( blob.size > 0 ? blob : "file creation error" )
};
createFile()
billbitt
  • 151
  • 12
guest271314
  • 1
  • 15
  • 104
  • 177