Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

116
Views
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?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!