How do I detect a browser or tab closing using router deactivate in Angular?

1 minute read

There is no built-in way to detect when the browser or tab is closed in Angular, but you can use the window object’s ‘beforeunload’ event to trigger an event before the browser tab closes.

In the below sample code, we have used the ‘hasChanges()’ method to return the ‘true’ status, and the canDeactivate method will be called before moving to the next route. The canDeactivate() method returns true so that the user is allowed to leave the page, but the confirmation dialogue is displayed first.

Typescript:

import { Component } from '@angular/core';
import { Router, ActivatedRoute } from '@angular/router';

@Component({
  selector: 'app-component',
  template: '...',
})
export class AppComponent {
  constructor(private router: Router, private route: ActivatedRoute) {}

  /**
  * Router Guard to determine if the page can be navigated away.
  */
  public canDeactivate(): boolean | Promise<boolean> | Observable<boolean> {
    if (!hasChanges()) {
      return true;
    }
    return showConfirmationDialog();
  }

  /**
  * Detect the changes
  */
  hasChanges(){
    return true;
  }
}

Leave a comment