简体   繁体   中英

onbeforeunload not working within unload

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 onunload event is the absolute last event that fires when the user navigates away from the page or closes the browser.

Binding to the onbeforeunload event within the onunload event would be pointless, as this event has already occurred (hence the name onbeforeunload ). The solution would be to bind to the onbeforeunload event before the event actually happens, such as when the page loads.

Something like this (untested):

$(window).bind('beforeunload', function () {
    if ($('.submitAction').val() == "" && isChange) {
       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?";
    }
});

This line returns a string:

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?";

I think you meant:

return window.confirm("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 technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM