0

I'm looking for a way to warn the user if they navigate away (close browser, click back button) from a multi-page form before submitting the completed form. Each section of the form that resides on a different page route is saved in SessionStorage.

I'm using the onbeforeunload event to trigger the "unsaved changes" dialog, however, it doesn't trigger in Chrome unless the user interacts with the page and thus the condition (return the dialog if SessionStorage exists) is not checked and the dialog does not display.

Any alternatives, suggestions or wisdom is appreciated!

// Display dialog when user navigates away without submitting form
// isStoredData condition is never met in Chrome unless user interacts with page
window.onbeforeunload = function () {
  let isStoredData = sessionStorage.getItem("MyFormDataInSessionStorage");
  let isDirty = $scope.MyForm.$dirty;
  if (isDirty || isStoredData) {
    return "Your application will not be saved.";
  }
  return undefined; 
};

// Prevent unsaved changes dialog when form is submitted
$('form').submit(function () {
  window.onbeforeunload = undefined;
});
ngaffer
  • 63
  • 10
  • Possible duplicate of [Intercept page exit event](https://stackoverflow.com/questions/1704533/intercept-page-exit-event) – Fabien Greard Jun 19 '18 at 22:00

1 Answers1

0

You should use $(window).on like below snippet:

$(window).on('beforeunload', function() {
   //Write your logic here.
});
nithinmohantk
  • 459
  • 4
  • 11