Search code examples
javascriptreactjsonbeforeunload

can't trigger beforeunload event in react


I want to trigger the beforeunload event when the user clicks on the back button. I've set up event listeners for the beforeunload event, like so

useEffect(() => {
    const cb = (ev) => {
      ev.preventDefault();
      return (ev.returnValue =
        "Changes might not be saved. Are you sure you want to close?");
    };
    window.addEventListener("beforeunload", cb);

    return () => window.removeEventListener("beforeunload", cb);
  }, []);

Here's the code that detects when the back button is clicked:

const history = useHistory();

useEffect(() => {
    return () => {
      if (history.action === "POP") {
        //ACTION TO BE DONE
        console.log("hoho", history.action);
        window.dispatchEvent(new Event("beforeunload"));
      }
    };
  });

When I click on the back button, I can see 'hoho POP' but the event is not being triggered. How can I fix this?


Solution

  • My intention was to show the popup about losing unsaved changes that shows up when the beforeunload event is triggered. Although I still can't manage to trigger the beforeunload event, I managed to figure out a workaround of sorts.

    Instead of me triggering the event, I simply used the Prompt component of react router, like so:

    <Prompt message="Leaving this page will cause you to lose unsaved data. Are you sure?" />
    

    Refer to react-router docs for more info on this component