Using Javascript to check if a file has been downloaded
Am working on an application which has a link to download a file. Am trying to create a functionality using Javascript whereby I want to detect immediately the file has been downloaded then perform some extra task. I have tested by downloading a file but it doesnt throw the alert box.
$( "a#policyDownload" ).mousedown(
function(e) {
//Get current time
var downloadID = ( new Date() ).getTime();
// Update the URL that is *currently being requested
$( "a#policyDownload" ).href += ( "?downloadID=" + downloadID );
//search for the name-value pattern with the above ID.
var cookiePattern = new RegExp( ( "downloadID=" + downloadID ), "i" );
//watch the local Cookies to see when the download ID has been updated by the response headers.
var cookieTimer = setInterval( checkCookies, 500 );
//check the local cookies for an update.
function checkCookies() {
// If the local cookies have been updated
if ( document.cookie.search( cookiePattern ) >= 0 ) {
clearInterval( cookieTimer );
alert('Downloaded');
}
}
}
);
In which case, you'd need to continually poll the server-side to know the status of that file download.
That's because cookies are sent along with an HTTP request: a page download, polling a JSON endpoint. The page you're on already received its cookies, and will only get updated cookies from the server with a page reload.
So instead of using cookies, I'd just poll (each 3 seconds) a JSON endpoint that would return the server-side determination of download completion.