-1

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?

Charlie
  • 22,886
  • 11
  • 59
  • 90
Ahmad Badpey
  • 6,348
  • 16
  • 93
  • 159
  • 1
    you can't use `confirm` or `alert` inside `onbeforeunload`. Many browsers won't even use the returned string as display. That function was so abused years ago that there is very little you can do inside it – charlietfl Jan 12 '16 at 10:05
  • 1
    Possible duplicate of [confirm() on window.onbeforeunload](http://stackoverflow.com/questions/12132060/confirm-on-window-onbeforeunload) – Manasov Daniel Jan 12 '16 at 10:07
  • 1
    Please use no pop-ups when user tries to close the tab! This is one of the worst available techniques. It's super annoying when you try to just close a tab but a popup tries to hinder you. Instead how about automatic saving through AJAX or local memory, or detecting an exit intent by checking pointer position (most users click on the x in the tab or window frame). Also keep in mind that most browsers remember what you typed in forms. – Hubert Grzeskowiak Jan 12 '16 at 10:09
  • @ManasovDaniel, your suggested topic was not my problem solution – Ahmad Badpey Jan 12 '16 at 10:12
  • 1
    @Hubert Grzeskowiak- depending upon the application, for unsaved data I believe it is acceptable at times- coupled with autosaving to reduce the instances of this happening. Not saying just because they do it it is ok, but Facebook and Gmail are two examples that spring to mind where this happens – Dave Pile Jan 13 '16 at 10:12

1 Answers1

1

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.

Charlie
  • 22,886
  • 11
  • 59
  • 90