Search code examples
javascriptjqueryhtmlconfirm

How can I determine when the page exits is because of form submiting?


Here is my code:

// confirm alert before close page
window.onbeforeunload = function(evt) {
    var el = document.getElementById("qandatextarea");
    if( el && el.value && !DontAskBeforeExit){
        var message = 'are you sure you want to exit this page?';
        if (typeof evt == 'undefined') {
            evt = window.event;
        }
        if (evt) {
            evt.returnValue = message;
        }

        return message;
    }
}

Please focus on this line:

if( el && el.value && !DontAskBeforeExit){

Well there is three conditions:

  • el: checks whether is that textarea exists in the DOM ?

  • el.value: checks has that textarea any value? (in other word, isn't that textarea empty?)

  • !DontAskBeforeExit: it is a variable which is either 0 or 1. When the content of that textarea is stored into localStorage, it is 1, otherwise it is 0.

Ok, now I need to one more condition. I need to check "is the page submitting or exiting"? I mean, I don't need to show that pop-up alert if the user is sending a post (submitting). How can I do that?


Solution

  • // set a flag so teh function isn't called twice on the form submit
    var formsubmitted = false;
    
    document.getElementById('myform').onsubmit = function(evt){
        formsubmitted = true;
        exitPage(evt, "formsubmit");
    };
    
    window.onbeforeunload = function(evt){
        // we don't want this to fire twice when the form is submitted
        if(!formsubmitted) exitPage(evt, "naturalunload");
    }
    
    // added an extra parameter , name, and condition to your original function
    function exitPage(evt, exitType) {
        var el = document.getElementById("qandatextarea");
        if( el && el.value && !DontAskBeforeExit && exitType=="formsubmit"){
            var message = 'are you sure you want to exit this page?';
            if (typeof evt == 'undefined') {
                evt = window.event;
            }
            if (evt) {
                evt.returnValue = message;
            }
    
            return message;
        }
    }