Detect when a browser receives a file download
Solution 1:
One possible solution uses JavaScript on the client.
The client algorithm:
- Generate a random unique token.
- Submit the download request, and include the token in a GET/POST field.
- Show the "waiting" indicator.
- Start a timer, and every second or so, look for a cookie named "fileDownloadToken" (or whatever you decide).
- If the cookie exists, and its value matches the token, hide the "waiting" indicator.
The server algorithm:
- Look for the GET/POST field in the request.
- If it has a non-empty value, drop a cookie (e.g. "fileDownloadToken"), and set its value to the token's value.
Client source code (JavaScript):
function getCookie( name ) {
var parts = document.cookie.split(name + "=");
if (parts.length == 2) return parts.pop().split(";").shift();
}
function expireCookie( cName ) {
document.cookie =
encodeURIComponent(cName) + "=deleted; expires=" + new Date( 0 ).toUTCString();
}
function setCursor( docStyle, buttonStyle ) {
document.getElementById( "doc" ).style.cursor = docStyle;
document.getElementById( "button-id" ).style.cursor = buttonStyle;
}
function setFormToken() {
var downloadToken = new Date().getTime();
document.getElementById( "downloadToken" ).value = downloadToken;
return downloadToken;
}
var downloadTimer;
var attempts = 30;
// Prevents double-submits by waiting for a cookie from the server.
function blockResubmit() {
var downloadToken = setFormToken();
setCursor( "wait", "wait" );
downloadTimer = window.setInterval( function() {
var token = getCookie( "downloadToken" );
if( (token == downloadToken) || (attempts == 0) ) {
unblockSubmit();
}
attempts--;
}, 1000 );
}
function unblockSubmit() {
setCursor( "auto", "pointer" );
window.clearInterval( downloadTimer );
expireCookie( "downloadToken" );
attempts = 30;
}
Example server code (PHP):
$TOKEN = "downloadToken";
// Sets a cookie so that when the download begins the browser can
// unblock the submit button (thus helping to prevent multiple clicks).
// The false parameter allows the cookie to be exposed to JavaScript.
$this->setCookieToken( $TOKEN, $_GET[ $TOKEN ], false );
$result = $this->sendFile();
Where:
public function setCookieToken(
$cookieName, $cookieValue, $httpOnly = true, $secure = false ) {
// See: http://stackoverflow.com/a/1459794/59087
// See: http://shiflett.org/blog/2006/mar/server-name-versus-http-host
// See: http://stackoverflow.com/a/3290474/59087
setcookie(
$cookieName,
$cookieValue,
2147483647, // expires January 1, 2038
"/", // your path
$_SERVER["HTTP_HOST"], // your domain
$secure, // Use true over HTTPS
$httpOnly // Set true for $AUTH_COOKIE_NAME
);
}
Solution 2:
A very simple (and lame) one line solution is to use the window.onblur()
event to close the loading dialog. Of course, if it takes too long and the user decides to do something else (like reading emails) the loading dialog will close.
Solution 3:
This solution is very simple, yet reliable. And it makes it possible to display real progress messages (and can be easily plugged in to existing processes):
The script that processes (my problem was: retrieving files via HTTP and deliver them as ZIP) writes the status to the session.
The status is polled and displayed every second. that’s all (OK, it’s not. You have to take care of a lot of details (for example, concurrent downloads), but it’s a good place to start ;-)).
The download page:
<a href="download.php?id=1" class="download">DOWNLOAD 1</a>
<a href="download.php?id=2" class="download">DOWNLOAD 2</a>
...
<div id="wait">
Please wait...
<div id="statusmessage"></div>
</div>
<script>
// This is jQuery
$('a.download').each(function()
{
$(this).click(
function() {
$('#statusmessage').html('prepare loading...');
$('#wait').show();
setTimeout('getstatus()', 1000);
}
);
});
});
function getstatus() {
$.ajax({
url: "/getstatus.php",
type: "POST",
dataType: 'json',
success: function(data) {
$('#statusmessage').html(data.message);
if(data.status == "pending")
setTimeout('getstatus()', 1000);
else
$('#wait').hide();
}
});
}
</script>
File getstatus.php
<?php
session_start();
echo json_encode($_SESSION['downloadstatus']);
?>
File download.php
<?php
session_start();
$processing = true;
while($processing) {
$_SESSION['downloadstatus'] = array("status" =>"pending", "message" => "Processing".$someinfo);
session_write_close();
$processing = do_what_has_2Bdone();
session_start();
}
$_SESSION['downloadstatus'] = array("status" => "finished", "message" => "Done");
// And spit the generated file to the browser
?>
Solution 4:
Based on Elmer's example, I've prepared my own solution. After elements click with defined download class it lets to show a custom message on the screen. I've used the focus trigger to hide the message.
JavaScript
$(function(){$('.download').click(function() { ShowDownloadMessage(); }); })
function ShowDownloadMessage()
{
$('#message-text').text('Your report is creating. Please wait...');
$('#message').show();
window.addEventListener('focus', HideDownloadMessage, false);
}
function HideDownloadMessage(){
window.removeEventListener('focus', HideDownloadMessage, false);
$('#message').hide();
}
HTML
<div id="message" style="display: none">
<div id="message-screen-mask" class="ui-widget-overlay ui-front"></div>
<div id="message-text" class="ui-dialog ui-widget ui-widget-content ui-corner-all ui-front ui-draggable ui-resizable waitmessage">please wait...</div>
</div>
Now you should implement any element to download:
<a class="download" href="file://www.ocelot.com.pl/prepare-report">Download report</a>
or
<input class="download" type="submit" value="Download" name="actionType">
After each download click you will see the message Your report is creating. Please wait...
Solution 5:
The core problem is that the web browser does not have an event that fires when page navigation is cancelled but does have an event that fires when a page completes loading. Anything outside of a direct browser event is going to be a hack with pros and cons.
There are four known approaches to dealing with detecting when a browser download starts:
- Call fetch(), retrieve the entire response, attach an
a
tag with adownload
attribute, and trigger a click event. Modern web browsers will then offer the user the option to save the already retrieved file. There are several downsides with this approach:
- The entire data blob is stored in RAM, so if the file is large, it will consume that much RAM. For small files, this probably isn't a deal breaker.
- The user has to wait for the entire file to download before they can save it. They also can't leave the page until it completes.
- The built-in web browser file downloader is not used.
- A cross-domain fetch will probably fail unless CORS headers are set.
- Use an iframe + a server-side cookie. The iframe fires a
load
event if a page loads in the iframe instead of starting a download but it does not fire any events if the download starts. Setting a cookie with the web server can then be detected by JavaScript in a loop. There are several downsides with this approach:
- The server and client have to work in concert. The server has to set a cookie. The client has to detect the cookie.
- Cross-domain requests won't be able to set the cookie.
- There are limits to how many cookies can be set per domain.
- Can't send custom HTTP headers.
- Use an iframe with URL redirection. The iframe starts a request and once the server has prepared the file, it dumps a HTML document that performs a meta refresh to a new URL, which triggers the download 1 second later. The
load
event on the iframe happens when the HTML document loads. There are several downsides with this approach:
- The server has to maintain storage for the content being downloaded. Requires a cron job or similar to regularly clean up the directory.
- The server has to dump out special HTML content when the file is ready.
- The client has to guess as to when the iframe has actually made the second request to the server and when the download has actually started before removing the iframe from the DOM. This could be overcome by just leaving the iframe in the DOM.
- Can't send custom HTTP headers.
- Use an iframe + XHR. The iframe triggers the download request. As soon as the request is made via the iframe, an identical request via XHR is made. If the
load
event on the iframe fires, an error has occurred, abort the XHR request, and remove the iframe. If a XHRprogress
event fires, then downloading has probably started in the iframe, abort the XHR request, wait a few seconds, and then remove the iframe. This allows for larger files to be downloaded without relying on a server-side cookie. There are several downsides with this approach:
- There are two separate requests made for the same information. The server can distinguish the XHR from the iframe by checking the incoming headers.
- A cross-domain XHR request will probably fail unless CORS headers are set. However, the browser won't know if CORS is allowed or not until the server sends back the HTTP headers. If the server waits to send headers until the file data is ready, the XHR can roughly detect when the iframe has started to download even without CORS.
- The client has to guess as to when the download has actually started to remove the iframe from the DOM. This could be overcome by just leaving the iframe in the DOM.
- Can't send custom headers on the iframe.
Without an appropriate built-in web browser event, there aren't any perfect solutions here. However, one of the four methods above will likely be a better fit than the others depending on your use-case.
Whenever possible, stream responses to the client on the fly instead of generating everything first on the server and then sending the response. Various file formats can be streamed such as CSV, JSON, XML, ZIP, etc. It really depends on finding a library that supports streaming content. When streaming the response as soon as the request starts, detecting the start of the download won't matter as much because it will start almost right away.
Another option is to just output the download headers up front instead of waiting for all of the content to be generated first. Then generate the content and finally start sending to the client. The user's built-in downloader will patiently wait until the data starts arriving. The downside is that the underlying network connection could timeout waiting for data to start flowing (either on the client or server side).