Search code examples
windowonbeforeunload

window close confirm behavior


I am using window.onbeforeunload = function() { return 'Ask question?'; };

to prevent accidentally window close without saving data.

Also the same page the form have a submit button (save button.)

I cannot figure it out how to avoid confirmation when submit button is press. Or maybe some kind of auto confirmation.


Solution

  • what you can do is to redefine the onsubmit event of your form by removing the onbeforeunload event before te sumbit itself:

    document.getElementById("yourFormId").onsubmit = function(){
        window.onbeforeunload = null;
        this.submit();
    }