Reputation: 101
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.
Upvotes: 7
Views: 2182
Reputation: 239
You have two possibilities to manage correctly the onbeforeunload event. You can either:
Upvotes: 4
Reputation: 101
I've managed to find a way around this that feels smooth and not quite as hacky as adding an iframe to download in.
I created a js variable (oldUnloadValue) outside my SystemInfo() function that i assign the original function in window.onbeforeunload. I then set window.onbeforeunload to a separate function i have created that will set window.onbeforeunoad back to it's original state. This let's the window.onbeforeunload fire with no ill effect during the file download but resets the functionality back once the download is complete.
var oldUnloadValue;
function SystemInfo() {
oldUnloadValue = window.onbeforeunload;
window.onbeforeunload = ResetOnBeforeUnload;
var url = 'xxxxx/about/SystemInfo?isajax=true';
window.location = formatURL(url);
};
function ResetOnBeforeUnload() {
window.onbeforeunload = oldUnloadValue;
};
Doing things this way has fixed my problem but still feels less ideal that it could be.
Upvotes: 2