43

I mean, I want to track when a user leaves the app, closing browser or tabs.

Components and Directives has a lifecycle hook called ngOnDestroy, which is called when the component is destroyed, but it can't catch when the user leaves the app

import { Component, OnInit } from '@angular/core';

@Component({
  moduleId: module.id,
  selector: 'app',
  templateUrl: 'app.component.html'
})
export class AppComponent implements OnDestroy {
  constructor() { }

  ngOnDestroy() {
      alert(`I'm leaving the app!`);
  }

}

If the user closes the browser, the alert is not executed.

Cœur
  • 34,719
  • 24
  • 185
  • 251
chamberin
  • 451
  • 1
  • 4
  • 6

1 Answers1

74

You can listen to the unload or beforeunload events like this:

export class AppComponent {
  @HostListener('window:unload', [ '$event' ])
  unloadHandler(event) {
    // ...
  }

  @HostListener('window:beforeunload', [ '$event' ])
  beforeUnloadHandler(event) {
    // ...
  }
}

See also

Sofia
  • 634
  • 10
  • 21
Günter Zöchbauer
  • 558,509
  • 191
  • 1,911
  • 1,506
  • 2
    it is possible to get only tab/browser close. – CTN Mar 20 '17 at 11:51
  • AFAIK there is only `unload` and `beforeunload`. There might be some tricks or hacks to get some more information, but I have no knowledge about. – Günter Zöchbauer Mar 20 '17 at 13:14
  • If you find any resource inform me. Thanks for quick response. :) – CTN Mar 21 '17 at 04:58
  • 10
    @GünterZöchbauer The above method is not working for me...i put an alert, but it is not triggering..angular version 2.4.10 – radio_head Jun 15 '17 at 16:19
  • 7
    The alert will never be showed.. since the dialog will be gone by that time. Put a breakpoint on the developer tools so you can see it being trigged. – jpgrassi Oct 02 '17 at 16:49
  • 1
    This event is also triggered on refreshing the page not only on closing tab. – Abdu Mar 13 '20 at 07:07