Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

123
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda