0

Is there a way to execute javascript function if user click "not leave" in beforeunload alert?

I use JQuery and the following code:

$(window).on('beforeunload', function (e) {
    if (formSubmitting || !isDirty()) {
        return undefined;
    }
    var confirmationMessage = 'You have unsaved work.';
    (e || window.event).returnValue = confirmationMessage; //Gecko + IE
    return confirmationMessage; //Gecko + Webkit, Safari, Chrome etc.
});

So how to check, if user stays on the page or leave it?

H.W.
  • 343
  • 1
  • 5
  • 21
  • possible duplicate of http://stackoverflow.com/questions/23522652/capture-the-result-of-window-onbeforeunload – ADyson Aug 15 '16 at 08:52
  • your function doesn't make sense, just returning any value (except `undefined`) results in the same outcome, i.e. a default alert dialog like "This page is asking you to confirm that you want to leave - data you have entered may not be saved." is shown. – Simon Hänisch Aug 15 '16 at 08:58
  • Simon Hänisch I edited it. I wanted to simplify it and did not realize this outcome. – H.W. Aug 15 '16 at 09:03

1 Answers1

0

When beforeunload confirmation dialog is shown to the user, there are two possibilities:

  • User leaves the page: in this case unload event is fired.

  • User stays on page: nothing will happen.

So, leaving can be detected by unload event, however staying cannot be detected by an event.

frogatto
  • 28,539
  • 11
  • 83
  • 129