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

544
Visualizações
onbeforeunload confirm dialog not showing when angular2 @HostListener is used

Using @HostListener hook, but confirm dialog (that asks: Do you want to Leave this page? ...or Do you want to Reload this page?) is not showing.

The code works, but the confirm dialog is not showing.

Here what I have:

@HostListener('window:beforeunload', ['$event'])
public doSomething($event) {
    console.log("do I see this?") // <---- this logs to the console.

    return "something else";
}

But I don't see this:

enter image description here

about 4 years ago · Santiago Trujillo
3 Respostas
Responde à pergunta

0

returning false instead of the string "something else" fixes the problem and the confirm dialog is shown.

It's quite possible that angular bindings modify the return value

about 4 years ago · Santiago Trujillo Relatório

0

For anybody still looking for another way to handle this in Angular. You can try doing this:

<router-outlet (window:beforeunload)="doBeforeUnload()" (window:unload)="doUnload()"></router-outlet>

Here I added the events to an event router-outlet bucause its the only thing in my app.component.html but you can add it to a container or wrapper. Also added both events because one beforeunload will only show the alert to the user when returning false and then unload handles the actual closing event. This is important because you may want to know what to do when the user continues or actually decides to close or handling unwanted clicks. The actual functions look like this:

doBeforeUnload() {
    // Alert the user window is closing 
    return false;
}

doUnload() {
    // Clear session or do something
    this.auth.getLogout();
}

PD: I tested this in Angular 6.

about 4 years ago · Santiago Trujillo Relatório

0

Instead of returning false you need to return $event.returnValue = "your text"

Modern browsers does not show your entered text.

@HostListener('window:beforeunload', ['$event']) 
yourfunction($event) {
    return $event.returnValue='Your changes will not be saved';
}
about 4 years ago · Santiago Trujillo 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