We might have observed in many sites that they ask user for confirmation upon closing the browser .
Ex : In gmail while we are composing an email if we closed browser tab or window, it will ask for confirmation.
We can implement same in our website by following the below listed steps.
Ex : In gmail while we are composing an email if we closed browser tab or window, it will ask for confirmation.
We can implement same in our website by following the below listed steps.
-
Create 2 variables named isNavigationAllowed and onNavigationMessage
var isNavigationAllowed=false; var onNavigationMessage="Closing the page will stop process, is it ok?";
-
Create a function named askForExit() with code given below
function askForExit() { if(!isNavigationAllowed) return onNavigationMessage; }
-
assign the function to window objects onbeforeload event
window.onbeforeunload = askForExit;
-
If we want this to confirm only when an operation in progress then we can handle with below code
//once upload started function uploadStarted() { window.onbeforeunload =askForExit; } //after completing upload function uploadDone() { window.onbeforeunload=function(){}; }
- The problem is this will ask when ever the current page is navigated
hence also requests for confirmation for Submit button and Links the solution is below- Add onsubmit attribute for the form
onsubmit="isNavigationAllowed=true;"
- Add onclick attribute for the links(a tags)
onclick="isNavigationAllowed=true;"
- Add onsubmit attribute for the form