Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Avoid firing window.onbeforeunload when downloading a file using an ajax call

I have a download button on my application information page that downloads a pdf. I also have the window.onbeforeunload event set for all pages to start my loading screen spinner and the window.onunload event kills the loading screen. The problem I'm having is that when I download my pdf file, the download works fine, but the window.onbeforeunload event is fired and not the window.onunload (as I'm not leaving the page). This causes my loading page to start when I download my file and never stop, making the page appear to hang on the download.

I'm downloading my SystemInfo.pdf file by using the below htm and javascript:

<a href="#" onclick="SystemInfo()">Download System Info</a>

function SystemInfo(){
    var url = 'xxxxx/about/SystemInfo?isajax=true';
    window.location = formatURL(url);
}

I have attempted to alter the link to use the 'download' attribute but that is not compatible with Safari and IE which is a requirement along with Chrome and Firefox. I have also added a dynamic iframe to fire the change in but have been told that's undesirable. Please let me know if you can help.

like image 800
Josh Goodwin Avatar asked Jul 10 '15 15:07

Josh Goodwin


1 Answers

You have two possibilities to manage correctly the onbeforeunload event. You can either:

  1. Add target="_blank": so onbeforeunload won't be fired
  2. or In your javascript SystemInfo function cancel your spinner immediatly or after a specific time
    • stopSpinner() or setTimeout(stopSpinner, 1000)
like image 153
Elie Nehmé Avatar answered Sep 28 '22 08:09

Elie Nehmé