I have a React application with a form component.
When a user fills in the form and tries to navigate away from the page in any way (closing tab, closing browser, refreshing page, pressing browser back button or any other navigation), I want to alert the user of unsaved changes.
I did the following -
useEffect(() => {
// do something
window.addEventListener("beforeunload", function (e) {
e.preventDefault();
e.returnValue = "";
});
return () => {
window.removeEventListener("beforeunload", function (e) {
e.preventDefault();
e.returnValue = "";
});
};
}, []);
This works when I try to close the browser, close tab or refersh the page. But when I press back button, I do not get any alert.
Is it that I cannot capture that back event due to security reasons? (FYI I am using Brave browser). If I can, what am I doing wrong here?