I use JavaScript function beforeunload to display a modal during the loading of the application. Code in my master page:
<script>
window.addEventListener("beforeunload", function (e) {
var modal = document.createElement("div");
modal.className = "modal-backdrop fade in"
modal.innerHTML = ' ';
var loader = document.createElement("div");
loader.className = "loader"
loader.innerHTML = '<i class="glyphicon glyphicon-hourglass"></i><br/><br/>Veuillez patienter...<br/>';
document.body.appendChild(modal);
document.body.appendChild(loader);
return null;
});
</script>
It works well except for a button event that generates an excel file. The end of the loading is not detected so the modal does not close.
For information I give the end of c# code of the button event:
Response.Write(style);
Response.Output.Write(sw.ToString());
Response.Flush();
Response.End();
I tried to call this function in my button event but it doesn't work :
function stopNavigate() {
window.onbeforeunload = null;
}
How can I disable the beforeunload for this button only ?
Turn the listener function into a standalone function that can be referenced elsewhere, so it's not anonymous. Then, you can remove it using removeEventListener
later. (Assigning null
to an on*
property will only remove a listener that was attached using the same on*
property)
function unloadHandler (e) {
var modal = document.createElement("div");
modal.className = "modal-backdrop fade in"
modal.innerHTML = ' ';
var loader = document.createElement("div");
loader.className = "loader"
loader.innerHTML = '<i class="glyphicon glyphicon-hourglass"></i><br/><br/>Veuillez patienter...<br/>';
document.body.appendChild(modal);
document.body.appendChild(loader);
return null;
}
window.addEventListener("beforeunload", unloadHandler);
// ...
function stopNavigate() {
window.removeEventListener('beforeunload', unloadHandler);
}