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

215
Visualizações
Removing beforeunload event in angular

I am trying to remove event using window.removeEventListener which I have added using window.addEventListener for event beforeunload but it is not getting removed. I am trying following code

addAlertWithListener(){

   window.addEventListener('beforeunload', (event) => {
     // Cancel the event as stated by the standard.
     event.preventDefault();
     // Chrome requires returnValue to be set.
     event.returnValue = 'You are currently in edit mode. Are you sure you want to refresh the page?';
  
   },true);
}

It is being added but when I am trying to remove the same function using below code :

 removeAlertWithListener() {
    window.removeEventListener('beforeunload', null,true);
  }

It still gives alert message. Am I missing something over here? I tried with and without last param. None of the thing seems working here.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

addEventListener and removeEventListener are implemented in a weird way in JavaScript, they need exactly the same parameters in order to retrieve the registered listeners. That's different from, like, setTimeout where an id is returned.

In Angular, usually I do something like this:

private readonly BEFORE_UNLOAD_PARAMS = ['beforeunload', (event) => ..., true];
private isBeforeUnloadActive: boolean = false;

addAlertWithListener() {
   if (this.isBeforeUnloadActive) return;
   window.addEventListener(...this.BEFORE_UNLOAD_PARAMS);
   this.isBeforeUnloadActive = true;
}

removeAlertWithListener() {
   window.removeEventListener(...this.BEFORE_UNLOAD_PARAMS);
   this.isBeforeUnloadActive = false;
}

The flag will prevent the listener to be registered twice

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