Site Overlay

How to handle hardware back button event and confirm by user to exit with Ionic and capacitor app

In this Ionic 5/4 + Capacitor tutorial. We’ll go through how to override the hardware back press event. Which shows a confirm alert dialog box. A user can prevent accidental exits by clicking on the cancel button or close the app by clicking on the exit button.

On a native Android device. A user may generally execute a variety of activities by tapping the back hardware button. Such as returning to the previous page, closing an overlay or dialog, or simply exiting the app.

The back press hardware action in most Ionic applications routes the application to the previous page; however, if there is no previous page in the stack, the user may mistakenly quit the application.

We’ll go through how to tweak the back hardware event’s behaviour by overriding it to show a beautiful confirm box with two action buttons Stay and Exit so that the user may stay on the app if they unintentionally hit the back button.

Note: In this article, we will 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.

Create a new ionic app

Before you go through this tutorial, you should have at least a basic understanding of Ionic Framework.

If you’re not familiar with Ionic Framework already, I’d recommend reading my How to install Ionic first for set up and running and understand the basic concepts.

let’s create a new ionic app with the ionic start command:

$ ionic start myApp tabs

Move inside the application directory

$ cd myApp

Run application

$ ionic serve --lab

Support of Ionic hardware back button event

Android applications that use Cordova and Capacitor supports back press event handling already . The Ionic framework application for PWA and browsers does not allow handling back press events.

How does the Ionic hardware back button event work?

When a user hits the back navigation button In an Ionic Capacitor application. the ionBackButton event is emitted.

We may register several handler callbacks under the ionBackButton event to conduct multiple operations in a sequence determined by a priority number.

So, when a user hits the back button, a confirm popup will appear using the register callback with priority 5, and if the user pushes the back button again, the second register callback with priority 10 will fire, maybe to allow the app to terminate.

Adding Back Handler with Confirm Exit Popup

We will add back press event handler to the App component. If the user is on an internal page, just browse back to the previous route. If the user is on the Home page, display an alert message with Stay and Exit buttons.

The isCurrentPathEqualTo() function determines if the current page is Home. if not, it returns to the previous page. Otherwise, use the showExitConfirm() method to display an Alert message.

Now, the app.component.ts file will look like following:

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();
      }
    });
  }

  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();
      });
  }

}

Add Capacitor/app Dependency

In Capacitor 3 it may close app directly on clicking hardware back button. So we have to @capacitor/app dependency to fix this issue.

npm install @capacitor/app
npx cap sync

Run Application on Device

Now execute the following command to generate a build of the application:

ionic build   
npx cap sync android

npx cap open android

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 to provide options to Stay or Exit.

Leave a Reply

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