How can we detect when user closes browser?

Solution 1:

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

  • Detect browser or tab closing
  • https://developer.mozilla.org/en-US/docs/Web/API/Window/unload_event