1

I use @HostListener('window:beforeunload') to detect if a user leaves the page. Then a dialog is opened. If she leaves, I want an event to be fired (or a method to be called). If the user does not leave, I don't want this event to be fired.

If I do:

  @HostListener('window:beforeunload')
  private someFunction() {
    WHATEVER
  }

someFunction is ALWAYS called. I want to know the user's answer before calling this function.

If I read this or this it seems these solutions should work also for my case, but I don't see how they handle the user's choice (whether leave or stay) to know if the function has to be called or not.

Could it be it's related with the $event I'm not using in @HostListener('window:beforeunload', ['$event'])?

Tony Ngo
  • 19,166
  • 4
  • 38
  • 60
xavier
  • 1,860
  • 4
  • 18
  • 46

1 Answers1

0

You can implement canDeactivate guard like this You can add confirm to detect user chose ok or cancel like this

canDeactivate(component: ComponentCanDeactivate): boolean | Observable<boolean> 
{
  let confirmObject = confirm("You want to leave ?");
  if (confirmObject  == true) {
    //call some thing then return true;
    return true;
  } 
  else {
    return false;
  }
}

Update maybe you can try with the same code of canDeactivate

@HostListener('window:beforeunload')
  private someFunction() {
    let confirmObject = confirm("You want to leave ?");
    if (confirmObject  == true) {
      //call some thing then return true;
      return true;
    } 
    else {
      return false;
    }
  }
Tony Ngo
  • 19,166
  • 4
  • 38
  • 60
  • That works if the user wants to leave the page using a link. Not when closing the browser, for example. This is when `window:beforeunload` is fired... – xavier Jun 27 '19 at 15:20
  • So you want to execute some function when user close browser ? – Tony Ngo Jun 27 '19 at 15:22
  • Close browser, close tab, change manually url... all the situations that are covered by `window:beforeunload`. – xavier Jun 27 '19 at 15:25
  • Well, I didn't try it yet but I think now you'll have 2 confirmation popups, which is not nice by itself, and moreover, the user could say "leave" in the first one and "stay" in the second... What I want is to get the response of the `window:beforeunload` popup. – xavier Jun 27 '19 at 15:35
  • No I mean you can try either 2 ways I provide you – Tony Ngo Jun 27 '19 at 15:36
  • No, what I meant is that you'll have now the confirm message and then the one provided by the browser (beforeunload). At the end of the day, however, confirm inside the function is ignored and I just get the browser popup. – xavier Jun 27 '19 at 15:44