Handling Hardware Back Button in Ionic

September 29th 2017 Ionic Framework Android

Ionic applications have built-in support for Android's hardware back button:

  • For non-root pages the button navigates back the navigation stack.
  • For the root page it closes the application.

There are ways to change that behavior, though.

If you only want to prevent the application from closing when the user presses the back button on the root page, you can use the navExitApp configuration option. You set it as an argument to the IonicModule import:

@NgModule({
  // ...
  imports: [
    BrowserModule,
    IonicModule.forRoot(MyApp, {
      navExitApp: false
    })
  ]
  // ...
})

If your application can have multiple different pages set as root depending on its state (e.g. login page for anonymous users and starting page for authenticated users) and don't want the back button to behave the same on all of them, you can selectively override the button using Platform.registerBackButtonAction:

import { Component } from '@angular/core';
import { Platform } from 'ionic-angular';

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

  private resetBackButton: any;

  constructor(private platform: Platform) { }

  ionViewDidEnter() {
    if (this.resetBackButton) {
      this.resetBackButton();
    }
    this.resetBackButton = this.platform.registerBackButtonAction(null);
  }

  ionViewWillLeave() {
    if (this.resetBackButton) {
      this.resetBackButton();
      this.resetBackButton = null;
    }
  }
}

The method returns a callback, which you need to call in order to restore the previous behavior of the back button. In the code above I change the behavior when entering the page and restore it again when leaving the page.

I pass null as the argument to Platform.registerBackButtonAction. This disables the back button on this page.

I could however pass it a function that I want to call. For example, I could send the application to background instead of closing it. There's a Cordova plugin, which will do that for me. I first need to install it:

cordova plugin add cordova-plugin-backbutton --save

I can then invoke it from the back button action:

this.resetBackButton = this.platform.registerBackButtonAction(() => {
  (navigator as any).Backbutton.goHome();
});

There's no type information available for the plugin, therefore I had to cast navigator to any so that the TypeScript compiler didn't complain. I could write an Ionic Native wrapper for the plugin instead.

Copyright
Creative Commons License