I have a page that allows the user to download a dynamically-generated file. It takes a long time to generate, so I\'d like to show a \"waiting\" indicator. The problem is,
"How to detect when browser receives file download?"
I faced the same problem with that config:
struts 1.2.9
jquery-1.3.2.
jquery-ui-1.7.1.custom
IE 11
java 5
My solution with a cookie:
- Client side:
When submitting your form, call your javascript function to hide your page and load your waiting spinner
function loadWaitingSpinner(){
... hide your page and show your spinner ...
}
Then, call a function that will check every 500ms whether a cookie is coming from server.
function checkCookie(){
var verif = setInterval(isWaitingCookie,500,verif);
}
If the cookie is found, stop checking every 500ms, expire the cookie and call your function to come back to your page and remove the waiting spinner (removeWaitingSpinner()). It is important to expire the cookie if you want to be able to download another file again!
function isWaitingCookie(verif){
var loadState = getCookie("waitingCookie");
if (loadState == "done"){
clearInterval(verif);
document.cookie = "attenteCookie=done; expires=Tue, 31 Dec 1985 21:00:00 UTC;";
removeWaitingSpinner();
}
}
function getCookie(cookieName){
var name = cookieName + "=";
var cookies = document.cookie
var cs = cookies.split(';');
for (var i = 0; i < cs.length; i++){
var c = cs[i];
while(c.charAt(0) == ' ') {
c = c.substring(1);
}
if (c.indexOf(name) == 0){
return c.substring(name.length, c.length);
}
}
return "";
}
function removeWaitingSpinner(){
... come back to your page and remove your spinner ...
}
- Server side:
At the end of your server process, add a cookie to the response. That cookie will be sent to the client when your file will be ready for download.
Cookie waitCookie = new Cookie("waitingCookie", "done");
response.addCookie(waitCookie);
I hope to help someone!