Ionic 3 Handle Back Press Button in Ionic 3 Application without Any Plugin

In Android application we generally press/ tap back to go back view or page but in root activity or root page in Ionic application this back press operation closes or minimize the application to the recent list.

In some application, it may have noticed a confirm pops up to confirm if you really want to close? to answer yes cancel. The ionic application also supports this feature when we can override android’s native back press event with ours.

After overriding we can tell then “Please press again to close/ exit application” or just show up an annoying prompt with yes/ cancel options.

We can implement in app’s main component or any single page or view. But the method will remain the same where ever you apply.

Let’s get started!

First to demonstrate we will create a new Ionic 3 application using below command

$ ionic start Ionic3BackPressDemo blank

Now we will add Platform module’s method registerBackButtonAction which overrides the native back press event after that we can implement our own logic when the user presses back.

    this.platform.registerBackButtonAction(() => {

      //This even will be called when user press/ tap Back key 
      
    });

You can add above back press event listener in a specific view component or in app’s main component file app.component.ts as follows

Implementation in a specific view like home.ts

import { Component } from '@angular/core';
import { NavController, Platform, App } from 'ionic-angular';
import { IonicPage } from 'ionic-angular';

@IonicPage()
@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {

  // This property will save the callback which we can unsubscribe when we leave this view
  public unsubscribeBackEvent: any;

  constructor(
    public platform: Platform,
    public navCtrl: NavController,
    public app: App
  ) {}

  //Called when view is loaded
  ionViewDidLoad() {
    this.initializeBackButtonCustomHandler();
  }

  //Called when view is left
  ionViewWillLeave() {
    // Unregister the custom back button action for this page
    this.unsubscribeBackEvent && this.unsubscribeBackEvent();
  }

  initializeBackButtonCustomHandler(): void {
    this.unsubscribeBackEvent = this.platform.registerBackButtonAction(function (event) {
        // you can add logic here to execute on backpress
    }, 101);
    /* here priority 101 will be greater then 100 
    if we have registerBackButtonAction in app.component.ts */
  }
}

In the above code, we are subscribing to Back button action on view load and keeping the instance in a property using which we will unsubscribe when user lease that view.

Implementation in app.component.ts

...
...
    platform.registerBackButtonAction(() => {
 
      let nav = app.getActiveNavs()[0];
      let activeView = nav.getActive();                
   
      //this will not work in signed version using Lazy load use activeView.id instead
      if(activeView.component.name === "HomePage") {
   
          // canGoBack check if these's and view in nav stack
          if (nav.canGoBack()){ 
              nav.pop();
          } else {
              let alert = this.alertCtrl.create({
                title: 'Exit Application?',
                message: 'Do you want to exit the application?',
                buttons: [
                  {
                    text: 'Cancel',
                    role: 'cancel',
                    handler: () => {
                      console.log('Cancel clicked');
                    }
                  },
                  {
                    text: 'Exit',
                    handler: () => {
                      console.log('Exit clicked');
                    }
                  }
                ]
              });
              alert.present();
          }
      }
  });

...
...

Also Read: Ionic Lazy Loading Issue | Get Current Component/ Page/ View name in Production Release

This back press event will have a priority of 100 by default. We have added an confirm box to exit.

So by using the above methods, we can easily handle back press event in Ionic application to give more usability to users.

 

 

Leave a Comment

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