Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

115
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda