Browser event when downloaded file is saved to disk Browser event when downloaded file is saved to disk javascript javascript

Browser event when downloaded file is saved to disk


This is a good solution:

http://gruffcode.com/2010/10/28/detecting-the-file-download-dialog-in-the-browser/

It basically works by setting a cookie in the reponse header of the downloaded file, so javascript periodically can check for the existence of this cookie...


There's no such browser event in JavaScript and even if there was you can not trust the user's browser to provide security for you.

You're better off using a GUID to generate a unique URL for each download. You can then for example:

  • let the URL be valid only for a specific time period
  • allow transfers only from a specific IP address associated with the unique URL
  • let your server-side code detect when the content for a unique URL has been fully transferred and then invalidate the URL.

Let me clarify the last bullet. Say you're using Java - you will in.read(buffer) and out.write(buffer) in a loop until EOF. If the client disconnects you will receive an IOException during out.write() and will be able to tell a successful download from an interrupted one. On other platforms, I'm sure there are ways to tell whether the connection was lost or not.

EDIT: You could actually fire a browser event using the trick outlined in the accepted answer of one of the questions you linked to. That would however not be a reliable solution to limit the number of downloads.


Why is it important that the file can be downloaded "exactly once"? Once the file is downloaded it could be copied, so is there really a security issue with letting the same user download the file more than once?

If not, could you do something like this:

  1. Generate a unique URL to download a given file. (Use a GUID to obsfucate if necessary)
  2. Associate that URL with USER INFO (browser type, IP address, etc) AND A TIME WINDOW. Only allow downloads from that user and during the window.
  3. The window should be long enough for the user to notice the transfer failed and to re-try once or twice, but no longer.

The end result is:

  1. You can be reasonably sure the file is only being downloaded by the intended recipient.
  2. You can be sure that recipient can only download the file during a short window.
  3. The same user could download the file more than once, but who cares? It's no different than making a local copy of the first file.

If you're really worried about it, log each download request and run a scheduled report for files that were downloaded more than once. If anything looks fishy you can then examine security logs, talk to the user, etc.