Reputation: 561
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
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
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
ofhidden
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
orvisibilitychange
events when closing a tab (webkit bugs: 151610 and 151234), so in Safari you may need to also listen to thebeforeunload
event in order to detect a change to the hidden state. But since thebeforeunload
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