javascriptwindow.onunload

how to use onbeforeunload for back button but prevent on form submits and internal page redirects


I am trying to display a warning dialogue to the user if the back button is pressed. The following works OK, except I only want this to happen on the back button or reload. not on form submit redirects that occur throughout the application.

window.addEventListener("beforeunload", function (e) {
     e.returnValue = 'warning';
}

can anyone help with a solution? preferably javascript only, and not jQuery. thanks


Solution

  • Set a variable when you submit the form. Test for the presence of that variable in the beforeunload handler, and only set the return value if it has been set.