Ionic [2|3] | How to manage hardware back button event like a pro

Written by on October 22, 2017

Ionic [2|3] | How to manage hardware back button event like a pro

In this guide, I’m going to walk you through the process of handling Android hardware back-button in the Ionic Framework.

Warning: Before we go any further I want to make one thing clear. This tutorial is explicitly made for the Ionic framework. And when I say Ionic Framework I mean Ionic 2|3. If you came here looking for a tutorial that covers original Ionic Framework ver1, you may find it here.

The main issue of a hardware back-button is always a lousy timing. No matter how capable they are, application users will, sooner or later, unintentionally trigger a back-button event. This is something we want to prevent, as, no matter how perfectly configured, this act may deteriorate the usability of our application. For example, it may lead to application termination, and the last thing we want to do is to force application users out.

I will show you how we can use the Ionic framework registerBackButtonAction function to get full control over back-button triggering, just like a pro.

Funny titbit, this function holds the same name in the all previous Ionic iterations. Which is great until you need to find actual help or information, then it becomes a hell to search for (this is just a small complaint).

In the end, you will be able to do these:

  • Prevent back-button from terminating an app
  • Prevent back-button actions on per page basis – centralized solution
  • Prevent back-button actions on per page basis – separated solution

Note: If this tutorial was helpful, you need further clarification, something is not working or you have a request for another Ionic post? Furthermore, leave me a comment below if you don't like something about this blog, if something is bugging you, don't like how I'm doing stuff here. Feel free to comment below, subscribe to my blog, mail me to dragan.gaic@gmail.com. Thanks and have a nice day!

Table of Contents

Ionic 2 is causing you problems? Are you struggling to make it work? Trust me, I wasn’t in any better situation. If you require more information beyond the subject of this article you will probably find it in a list below. Take a look; if there’s a topic not covered here, leave me a comment and I’ll cover it.

[spoiler title=” Click here if you want to see a list of topics covering Ionic 2 framework”]

Introduction to Object Oriented JavaScript

Ionic 2 Tutorials


[/spoiler]

Preparations

You should have everything set up and working before we can begin.

Make sure you have these:

  • Android Environment (or iOS if you’re working on a MacOS)
  • nodeJS
  • Ionic 2
  • Cordova

Find more information here: IONIC 2 | INSTALLATION GUIDE if you don’t have a previous Ionic 2 installation or if you have never read my previous articles on this topic.

1. Update Ionic & Cordova

As we are working with the NodeJS make sure you have the latest version, without it, you’ll not be able to install/update Cordova and Ionic appropriately. Worst case scenario, have as recent version as possible.

If you already have a working Ionic environment make sure it’s up to date, older versions may not work with this guide. Though sometimes, the latest versions may also mess things up, it’s up to you:

npm install -g ionic cordova

or to do a simple update:

npm update -g ionic cordova

2. Create A New Project

ionic start IonicBackButtonHandleExample blank
cd IonicBackButtonHandleExample

You can find a working example at the end of this article if you’re an impatient type. Just follow the provided README.md instructions.

Warning: As some of you don't have a prior Ionic CLI experience, from this point and on, every time I tell you to execute something, do that inside an example project folder.

3. Add A Required Platform

As this is only an Android guide:

ionic cordova platform add android

Source Walkthrough

Compared to Ionic Framework v1, the current implementation is pretty straightforward. Only thing you need to do is use this piece of code:

platform.registerBackButtonAction(() => {

});

Function registerBackButtonAction accepts also one more parameter called priority, but we will talk more about it a little bit later.

The return result of this function in another function, which will when called, unregister previously configured back-button event:

ionViewWillLeave() {
	// Unregister the custom back button action for this page
	this.unregisterBackButtonAction && this.unregisterBackButtonAction();
}

initializeBackButtonCustomHandler(): void {
	this.unregisterBackButtonAction = this.platform.registerBackButtonAction(function(event){
		console.log('Prevent Back Button Page Change');
	}, 101);
}   

As you can see in the above example, we can use this unregister function and call it on the ViewLeave event (in our case it’s a function), or when you want to restore the default behavior.

We have also use a priority 101 there. Priority 101 will override back button handling ( the one we set in app.component.ts) as it is bigger then priority 100 configured in app.component.ts file.

This also tells you that we can configure back-button event in several places. For example, we can do this on per page level:

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

@IonicPage()
@Component({
  selector: 'page-second',
  templateUrl: 'second.html',
})

export class SecondPage {

    // Property used to store the callback of the event handler to unsubscribe to it when leaving this page
    public unregisterBackButtonAction: any;

	constructor(public navCtrl: NavController, public navParams: NavParams, public platform: Platform) {

	}

	ionViewDidLoad() {
		this.initializeBackButtonCustomHandler();
	}

    ionViewWillLeave() {
        // Unregister the custom back button action for this page
        this.unregisterBackButtonAction && this.unregisterBackButtonAction();
    }

    initializeBackButtonCustomHandler(): void {
		this.unregisterBackButtonAction = this.platform.registerBackButtonAction(function(event){
			console.log('Prevent Back Button Page Change');
		}, 101); // Priority 101 will override back button handling (we set in app.component.ts) as it is bigger then priority 100 configured in app.component.ts file */
    }    	
}  

This approach is excellent if you prefer to decouple your code.

On the other hand, you can do everything in one place. In our case, it’s going to be app.component.ts as it is a central point of our application:

platform.registerBackButtonAction(() => {

	let nav = app.getActiveNavs()[0];
	let activeView = nav.getActive();                

	if(activeView.name === "FirstPage") {

		if (nav.canGoBack()){ //Can we go back?
			nav.pop();
		} else {
			const alert = this.alertCtrl.create({
				title: 'App termination',
				message: 'Do you want to close the app?',
				buttons: [{
					text: 'Cancel',
					role: 'cancel',
					handler: () => {
						console.log('Application exit prevented!');
					}
				},{
					text: 'Close App',
					handler: () => {
						this.platform.exitApp(); // Close this application
					}
				}]
			});
			alert.present();
		}
	}
});

For this implementation to work, you first need to import App component, as we will use it to acquire current view name:

import { App } from 'ionic-angular';

constructor(public  app: App) {

The rest is easy, depending on a view name we will trigger a different back-button even result:

if(activeView.name === "FirstPage") {

	if (nav.canGoBack()){ //Can we go back?
		nav.pop();
	} else {
		const alert = this.alertCtrl.create({
			title: 'App termination',
			message: 'Do you want to close the app?',
			buttons: [{
				text: 'Cancel',
				role: 'cancel',
				handler: () => {
					console.log('Application exit prevented!');
				}
			},{
				text: 'Close App',
				handler: () => {
					this.platform.exitApp(); // Close this application
				}
			}]
		});
		alert.present();
	}
}

In our case we’re showing an alert which gives us a choice will we close the app or not.

One bit of warning, this solution requires at least Ionic 3.5.3. version. To be more specific, function app.getActiveNav() is deprecated and we are now using app.getActiveNavs().

If you are using an older Ionic version use this piece of code instead:

let nav = app.getActiveNav();
let activeView = nav.getActive().name;
Continue to the next page

Categories

6 thoughts on “Ionic [2|3] | How to manage hardware back button event like a pro”

  1. hey sir plz help me i am using your centralized methord in a tab project everythting is working in debug apk but after production build nothing works. plz help me as soonn as possible sir

  2. sir if you want me to send the code i will mail u plz help i am new to ionic. plz give me your email id. iwill send u the code

  3. Hello, thank you for this tutorial! would you please one for handling hardware home button on Ionic? I want to make sure my app completely shuts down on using home button… my current app is running in background when I exit using home button.
    Thanks,

Leave a Reply