Drag to Desktop in JS

Paul Kinlan

When I created appmator, I want to remove a lot of the traditional webism that we see in apps. Specifically, I am not overly keen on “Save As” buttons, so I made sure I didn’t include one in the application

The question then becomes how do you get data quickly to a directory of the users choice. I have chosen two operations, a standard click of a url that downloads the data clientside (another post to come shortly). Chrome has a feature, its Drag and Drop implementation allows you to specify a URI or Data URI that is attached to a drag operation, specifically a drag operation that ends outside the browser. When Chrome detects that the drag operation has ended outside the browser

var element = document.getElementById("anyoldelement");
anyoldelement.addEventListener("dragstart", function(e) {
   e.dataTransfer.setData("DownloadURL",
       "application/zip:package.zip:data:image/png;base64," +
       Builder.output({"binary": false}));
});

It is pretty simple, we attach a function to the ondragstart event. That function simply sets the sets Data on the dataTransefer object in the event callback. The data is of a specific type called “DownloadURL” and attaches a valid URI – this URI can be anything in the domain, or it can be a DataURI (as in the case of this example). Prior to the URI is the meta-data about the URI, in this case it is application/zip:package.zip which is a simple MIME type and file name.

The code that generates the dataURI is part of a library function that generates a ZIP file (JSZip in fact, which is an awesome library)

And that is pretty much it.

In honesty, this approach only works in Chrome, so be warned. Also, it is impossible to detect the presence of this feature.

Paul Kinlan

Trying to make the web and developers better.

RSS Github Medium