0

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?

vaibhav deep
  • 655
  • 1
  • 8
  • 27

1 Answers1

0

you can try to subscripe onhashchange event.

Here is thread with a similar query:

How to Detect Browser Back Button event - Cross Browser