I am currently working on a website and there is a page with a form. When the user tries to leaves this page, I want a confirmation message to show up. This is how I did it:
In the JSP file (the website is made with Struts2):
<body onbeforeunload="return onUnload()">
The JavaScript code:
function onUnload() {
var confirmationMessage = 'It looks like you have been editing something. '
+ 'If you leave before saving, your changes will be lost.';
if (formSubmitting) {
return undefined;
}
return confirmationMessage;
}
This works fine if you try to reload the page or click on a link, but if you try to enter the form and then click on the back button of the browser, Firefox and Chrome return to the previous page without displaying the message. The only good guy here is Edge, who displays the message as expected.
Also, if I click the back button after I tried to leave the page via a link or tried to reload the page, the message is displayed in all the browsers.
I usually don't do software development, which might explain why I don't understand why these three browsers don't behave the same way here. So, some help from you guys is welcome.
EDIT: I don't want to detect the back button. All I want is for the browser to show the confirmation message when the user leaves the page, which right now does not happen if he clicks the back button.