views:

75

answers:

2

How do I check if the user accepted a file download in JavaScript. Example: If the site pops up a download link, and the web browser asks the user to download the file, how do I determine on that page if the user accepted the download or not?

+2  A: 

JavaScript will not have access to that information. In general, JavaScript inside web browsers is limited to simply interact with the DOM.

You may be able to do something on the server-side that logs the start of the download stream, but as @Pointy and @Marcel noted in comments to another answer, this could be quite tricky. In such a case, you would then be able to ask the server for this information using AJAX, or long polling, etc, in near real-time.

Daniel Vassallo
It's possible to get a pretty good idea that the download has *started*, but you're right that you can't tell whether the user accepted it.
Pointy
A: 

You will have to do it indirectly by checking the web server log file via an AJAX call. This will require you to write some server side code (and you must have access to the log files).

There's a second way of doing it, and that's to stream the file through a server side program. That way you can set a flag when the file has started to stream and retrieve this flag via an AJAX call.

Gert G
There's a major flaw in the first case: at least in Firefox the download starts as soon as I click a link. During the time I select a place to save that file, it could have been (entirely) downloaded before I press the Cancel button.
Marcel Korpel
The problem is that the file will *start* to stream at the very beginning of the HTTP response. The browser puts up it's "What to do with the file" dialog *after* the bytes have already started to arrive. Due to buffering all along the way from server to client, a whole lot of the file may get shipped out even if the user chooses not to save the file.
Pointy
@Marcel It's not something determined by the browser. The server responds to the HTTP request with the actual bytes of the download file. There's no further communication with *any* browser as to the "save/don't save" decision.
Pointy
Good point, Pointy.
Gert G