Angular 10 Leave Browser Beforeunload Event: Warn Users Leaving your App

Angular 10 Leave Browser Beforeunload Event: Warn Users Leaving your App

In this article, we'll learn about the beforeunload event which is a browser event that's used to prompt or warn users that they're about to leave a page or in our case the Angular app.

Angular 10 Leave Browser Beforeunload Event

How to Use beforeunload in JavaScript

You can use the browser's beforeunload event in JavaScript to prompt users that they're going to close the page as follows:

window.addEventListener('beforeunload', (event) => {
  event.returnValue = `You have unsaved changes, leave anyway?`;
});

How to Use beforeunload in Angular

In Angular, you can either use the CanDeactivate route guard to warn users when they are about to leave the current route/page to another page in the app but you need to use the beforeunload event if you need to watch for the tab closing or the whole app refreshing

Just like plain JavaScript, you'll need to add a listener to the beforeunload window event using either JavaScript' addEventListener method (Not very recommended) or the Angular APIs such as HostListener. For example, you can add the following code in a component:

@HostListener('window:beforeunload', ['$event'])
unloadHandler(event: Event) {
    // Your logic on beforeunload
}

You can also bind a method to the window:beforeunload event of a DOM element inside your page as follows:

<div (window:beforeunload)="onBeforeUnload()"></div>

✋If you have any questions about this article, ask them in our GitHub Discussions 👈 community. You can also Gitter

✋ Want to master Angular 14? Read our angular tutorial and join our #DailyAngularChallenge where we learn to build components, directives, services, pipes and complete web, mobile, and desktop applications with latest Angular version.

✋ Make sure to join our Angular 14 Dev Community 👈 to discuss anything related to Angular development.

❤️ Like our page and subscribe to our feed for updates!