I have wrote the following code to run the onbeforeunload within unload. However, this doesn’t seem working. Does anyone know what’s wrong about my code and anyway to make it work?
$(window).unload(function () {
if ($('.submitAction').val() == "" && isChange) {
window.onbeforeunload = confirmExit;
}
});
function confirmExit() {
return "If you have made any changes to the fields without clicking the Save button, your changes will be lost. Are you sure you want to exit this page?";
}
The
onunloadevent is the absolute last event that fires when the user navigates away from the page or closes the browser.Binding to the
onbeforeunloadevent within theonunloadevent would be pointless, as this event has already occurred (hence the name onbeforeunload). The solution would be to bind to theonbeforeunloadevent before the event actually happens, such as when the page loads.Something like this (untested):