How can we detect when the user closes the browser?

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

Components and directives have a lifecycle hook called ngOnDestroy, which is called when the component is destroyed, but it cannot catch when the user leaves the application.

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 warning is not executed.

+8
angular
source share
1 answer

You can listen to unload or beforeunload as follows:

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

see also

+16
source share

All Articles