chamberin
chamberin

Reputation: 561

How can we detect when user closes browser?

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.

Upvotes: 54

Views: 87659

Answers (2)

Günter Zöchbauer
Günter Zöchbauer

Reputation: 657268

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

Use IDE breakpoints to verify triggers.

Upvotes: 84

jyrkim
jyrkim

Reputation: 2869

visibilitychange event is an alternative

export class AppComponent {
   
  @HostListener('document:visibilitychange', ['$event']) 
  visibilityChange($event: Event) {
    
    if (document.visibilityState === 'hidden') {
      console.log("document.visibilityState === 'hidden'")
    }
  }
}

MDN usage notes for visibilityState say (May 31, 2022) :

This event fires with a visibilityState of hidden when a user navigates to a new page, switches tabs, closes the tab, minimizes or closes the browser, or, on mobile, switches from the browser to a different app.

For Safari beforeunload event is also recommended at Chrome Developers Blog: Page Lifecycle API by Philip Walton (May 27, 2020 ):

Safari does not reliably fire the pagehide or visibilitychange events when closing a tab (webkit bugs: 151610 and 151234), so in Safari you may need to also listen to the beforeunload event in order to detect a change to the hidden state. But since the beforeunload event can be canceled, you need to wait until after the event has finished propagating to know if the state has changed to hidden.

Upvotes: 1

Related Questions