Search code examples
javascriptjqueryformsconfirm

Confirm user to submit a form before page closing via jquery


I want to get the confirmation from the user to save a form before page closing with confirm() javascript function. If user pressed Ok button, run save form action and if pressed Cancel button, then close page.

for that I write this :

window.onbeforeunload = function() {
    if (confirm('Are you want to save Form ?')){
        //saveActions
    }
    return 'You have unsaved changes!';
}

But onbeforeunload event for window object does not run confirm() function and jsut it's own confirmation dialog box with string that is next to return instruction.

How can I do that?


Solution

  • This is natural behavior.

    window.onbeforeunload is restricted in operation to prevent it being exploited.

    Discouraging or polling the user for opinion after the final closing action is a bad practice.

    Try options like periodically saving your data, having inner "Close" button etc.