How to handle file dragging in a Firefox web app


One of the things I miss most when moving from a desktop app to the web is the ability to drag and drop documents between programs. The default file open dialog within a form is definitely not an adequate substitute. The best you can manage with a plain web app is dragging elements within the same page.

To add the full functionality to a web application, you need to install some client-side code. In Firefox, the easiest way to do this is with an extension, though a signed JAR file containing the script is also a possibility. I haven’t tried to do it in IE yet, so that will have to wait for another post.

Here’s an example extension, with full source code and a test page demonstrating how to use it. To try it out:

  • Install draganddrop.xpi in Firefox
  • Load testpage.html
  • Try dragging some files onto the different text areas on the page

You should see an alert pop up with the file path and the element’s text when you do this. The extension adds a new event type to FireFox; "PeteDragDropEvent". When a file is dragged onto a web page, it sets the element underneath the mouse’s ‘dragdropfilepath’ attribute, and then fires the event on that element. If the element has called addEventListener for that event previously, then its defined handler function will be called, and the script can do what it needs to.

The main drawback is that you only get access to the local file path for the dragged object, and there’s not much an external web script can do with that. I’ll cover the options you have to do something interesting, like uploading a file to a server, in a future post.

This page was invaluable when I was developing the extension, it has a great discussion with examples of the mechanics of Firefox’s drag and drop events. One thing to watch out for if you reuse this extension for your own projects is that you don’t want to open up dragging-and-dropping for all pages. That would be a possible security problem if malicious sites lured users into dragging onto them. Instead you should do some URL white-listing to make sure only trusted locations are allowed, being careful to properly parse the address so that spoofing with @, etc, won’t fool the test.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: