How to disable beforeunload action when user is submitting a form?

前端 未结 7 2265
伪装坚强ぢ
伪装坚强ぢ 2020-11-28 12:48

I have this little piece of code:



        
相关标签:
7条回答
  • 2020-11-28 13:06

    Super old question but might be useful to others.

    Simply detaching the "beforeunload" from the "submit" event would not work for me - because the submit handler was being called even when there were errors in the form that the user had to fix. So if a user attempted to submit the form, then received the errors, then clicked to another page, they would be able to leave without the warning.

    Here's my workaround that seems to work pretty well.

    (function($) {
    
        var attached = false,
            allowed = false;
    
        // catch any input field change events bubbling up from the form
        $("form").on("change", function () {
            // attach the listener once
            if (!attached) {
                $("body").on("click", function (e) {
                    // check that the click came from inside the form
                    // if it did - set flag to allow leaving the page
                    // otherwise - hit them with the warning
                    allowed = $(e.target).parents("form").length != 0;
                });
    
                window.addEventListener('beforeunload', function (event) {
                    // only allow if submit was called 
                    if (!allowed) {
                        event.preventDefault();
                        event.returnValue = 'You have unsaved changes.';
                    }
    
                });
            }                
            attached = true;
        });
    
    }(jQuery));
    

    This way, if the click to leave the page originated from inside the form (like the submit button) - it will not display the warning. If the click to leave the page originated from outside of the form, then it will warn the user.

    0 讨论(0)
提交回复
热议问题