For anybody still looking for another way to handle this in Angular. You can try doing this:
<router-outlet (window:beforeunload)="doBeforeUnload()" (window:unload)="doUnload()"></router-outlet>
Here I added the events to an event router-outlet bucause its the only thing in my app.component.html but you can add it to a container or wrapper. Also added both events because one beforeunload
will only show the alert to the user when returning false and then unload
handles the actual closing event. This is important because you may want to know what to do when the user continues or actually decides to close or handling unwanted clicks. The actual functions look like this:
doBeforeUnload() {
// Alert the user window is closing
return false;
}
doUnload() {
// Clear session or do something
this.auth.getLogout();
}
PD: I tested this in Angular 6.