Ionic 5 handle back hardware event to confirm exit by user

In this Ionic 5/4 tutorial, we’ll discuss how to override the hardware back press event in Ionic Application to show a confirm alert dialog box to the user. A user can click on cancel to prevent accidental exits and or tap on the exit button to close the application.

In native Android devices, a user usually performs various actions by tapping on the back hardware button on the bottom of the screen like moving back to the previous page, closing an overlay or dialog, or simply close the application.

Generally, the back press hardware action in Ionic application causes to route the application to the previous page, while doing this a user can accidentally exit the application when there is no previous page in the stack.

We’ll discuss how to customize this behavior of back hardware event by overriding it to show a sweet confirm box with two action buttons Stay and Exit so that the user can stay on the app if accidentally pressed the back button.

Note: In this article, we’ll are going to discuss the back hardware button which is available on Android devices at the bottom of the mobile phone. This is different to the back button icon which is displayed on the application page header on the top left corner.

 

Let’s start the implementation…

Install or Update the Ionic CLI

We are going to build a new Ionic application using the latest version of Ionic CLI for Ionic 5. Run the following command to update or install

$ npm install -g @ionic/cli

 

Create a new Ionic Angular app

Execute the following command to set up a new Ionic Angular application with a blank template

$ ionic start ionic-handle-back-event blank --type=angular

Move inside the application directory

$ cd ionic-handle-back-event

Run application

$ ionic serve --lab

 

Support of Back Press handler

Currently, the back press even handling is available in the applications using Cordova and Capacitor working on Android devices. Application build using Ionic framework for PWA and browsers does not support to handle back press event.

 

How does the Back Press Event work?

The Ionic applications using Cordova or Capacitor emits the ionBackButton event whenever a user taps on the back navigation button.

Under the ionBackButton event, we can register more than one handler callback to performs multiple operations in a series defined by a priority number.

So it works like this when a user taps back button first a confirm popup will show up using the register callback with priority 5, again if the user presses the back button then the second register callback with priority 10 will fire to maybe to let the app close.

 

How do we add a Back Press Event Handler?

In Ionic Angular application, we import the Platform class from @ionic/angular to provide the backButtom property to which we can subscribe as shown below:

import { Platform } from '@ionic/angular';

...

constructor(private platform: Platform) {
  this.platform.backButton.subscribeWithPriority(10, () => {
    console.log('Handler was called!');
  });
}

We can add multiple backButton event handlers with a priority. If

This is how we register an event handler emitted when a user press the hardware back button. As we have set the priority for this handler to 10, other handlers with priority more than 10 will be triggered first.

 

Adding Back Handler with Confirm Exit Popup

In the App component, we’ll add the back press event handler. There will be two event handlers as shown below:

this.platform.backButton.subscribeWithPriority(10, (processNextHandler) => {
    console.log('Back press handler!');

      processNextHandler();

  });

  this.platform.backButton.subscribeWithPriority(5, () => {
    console.log('Handler called to force close!');
  });

At first, the handler with priority 10 will fire, the processNextHandler() method will trigger the next back press handler with lower priority 5.

 

User Action Cases

Following two cases will be handled

Case 1) Show and Alert Popup if on Home Page

If the user is on any internal page, simply navigate to the previous route or it is on the Home page then show an alert message with buttons to Stay or Exit

this.platform.backButton.subscribeWithPriority(10, (processNextHandler) => {
      console.log('Back press handler!');
      if (this._location.isCurrentPathEqualTo('/home')) {

        // Show Exit Alert!
        console.log('Show Exit Alert!');
        this.showExitConfirm();
        processNextHandler();
      } else {

        // Navigate to back page
        console.log('Navigate to back page');
        this._location.back();

      }

    });

The isCurrentPathEqualTo() method is checking if the current page is Home, if not navigate back to the previous page. Otherwise display an Alert message by calling the showExitConfirm() method.

Also, we are calling the processNextHandler() method to activate immediate next lower priority handler when an alert is displayed. So that if the user hits back again the app will close.

 

Case 2) User Press back multiple times

When the user taps back even when Alert is shown, then the second handler will be served to check if the alert is open then simply exit the application. As the user intentionally wants to close the app.

this.platform.backButton.subscribeWithPriority(5, () => {
      console.log('Handler called to force close!');
      this.alertController.getTop().then(r => {
        if (r) {
          navigator['app'].exitApp();
        }
      }).catch(e => {
        console.log(e);
      })
    });

The getTop() will check if an alert is open, even then if the back is pressed the application will close by calling the navigator['app'].exitApp() method.

 

Finally, the complete app.component.ts file will look this:

// app.component.ts
import { Component } from '@angular/core';

import { Platform, AlertController } from '@ionic/angular';
import { SplashScreen } from '@ionic-native/splash-screen/ngx';
import { StatusBar } from '@ionic-native/status-bar/ngx';

import { Location } from '@angular/common';

@Component({
  selector: 'app-root',
  templateUrl: 'app.component.html',
  styleUrls: ['app.component.scss']
})
export class AppComponent {
  constructor(
    private platform: Platform,
    private splashScreen: SplashScreen,
    private statusBar: StatusBar,

    private _location: Location,
    public alertController: AlertController
  ) {
    this.initializeApp();
  }

  initializeApp() {
    this.platform.ready().then(() => {
      this.statusBar.styleDefault();
      this.splashScreen.hide();
    });


    this.platform.backButton.subscribeWithPriority(10, (processNextHandler) => {
      console.log('Back press handler!');
      if (this._location.isCurrentPathEqualTo('/home')) {

        // Show Exit Alert!
        console.log('Show Exit Alert!');
        this.showExitConfirm();
        processNextHandler();
      } else {

        // Navigate to back page
        console.log('Navigate to back page');
        this._location.back();

      }

    });

    this.platform.backButton.subscribeWithPriority(5, () => {
      console.log('Handler called to force close!');
      this.alertController.getTop().then(r => {
        if (r) {
          navigator['app'].exitApp();
        }
      }).catch(e => {
        console.log(e);
      })
    });

  }

  showExitConfirm() {
    this.alertController.create({
      header: 'App termination',
      message: 'Do you want to close the app?',
      backdropDismiss: false,
      buttons: [{
        text: 'Stay',
        role: 'cancel',
        handler: () => {
          console.log('Application exit prevented!');
        }
      }, {
        text: 'Exit',
        handler: () => {
          navigator['app'].exitApp();
        }
      }]
    })
      .then(alert => {
        alert.present();
      });
  }

}

 

That’s it this how you can handle the back press event on mobile hardware navigation.

 

Run Application on Device

You can download the source code of example application given in the next section, and run on a real device.

First, you need to create a build of the application by running below command:

$ ionic cordova build android

The above command will add the Android platform and create the application build.

Now, you can run the application on a real device connected to the PC via USB cable by hitting below command:

$ ionic cordova run android -l

 

Source Code

Download the source code of the sample Ionic 5 application on my GitHub repository here.

 

Conclusion

Finally, we have handled the Back press hardware event in our Ionic Angular application, in normal cases we are navigating to the previous page, but when the user is at the home page we are showing a prompt alert message using Ionic UI Component to provide options to Stay or Exit. Even then if the user press back the second handler will execute to close the application.

Hope you enjoyed the post and it is helpful, Do share with others and share your thoughts in the comment sections below.

 

8 thoughts on “Ionic 5 handle back hardware event to confirm exit by user”

  1. Thank you, thank you, thank you. There is very little documentation online on canGoBack and very little on this issue with Ionic 5, so your article really helped me. Thank you.

  2. I don’t know you, but I came to say that you saved me few times! Keep it up for the good work!
    Thank you!

  3. I used this code but when I put in ionViewWillLeave I get an error message saying this.unsubscribeBackEvent is not a function. Please let me know what it is that I am doing wrong. Everything else is working just as I would like it except this function.

    1. It’s work for me!
      ionViewWillLeave() {
      // Unregister the custom back button action for this page
      this.unsubscribeBackEvent;
      }

Leave a Reply to code android example Cancel Reply

Your email address will not be published. Required fields are marked *