Are you one of those people suffering nightmares because of what Android hardware back button is doing to your Ionic application? Fear not, here’s everything you need to know.
 
The main problem with the back button (I’m of course talking about hardware back button, there’s no point in repeating that) is usually a bad timing. Unless correctly configured, your application will (probably) handle a back event in a way you don’t prefer. For example, instead of closing popup it will close the entire application.
 
 

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

PS. If you want my help, if possible (even if it takes you some time to do that), create a working example I can play with. Use Plunker for AngularJS based questions or jsFiddle for jQuery/jQuery Mobile based questions.


 

Table of Contents

 
Click here if you want to see other tutorials, or articles about the Ionic framework (themes, templates, plugins, tutorials)
 

Introduction

 
By default, the Ionic framework provides a set of utility methods that can be used to retrieve the device ready state and various other information such as what kind of platform the app is currently installed on.
 
In our case, we will use an angular abstraction of ionic.Platform called $ionicPlatform. It can be used to detect the current platform, and what’s more important for us, override the Android back button in PhoneGap/Cordova.
 
This object provides three methods called:
 
  • onHardwareBackButton
  • offHardwareBackButton
  • registerBackButtonAction
 
Method onHardwareBackButton is used to bind a back button event, essentially this is a method you want to use to catch a back button action.
 
$ionicPlatform.onHardwareBackButton(function() {

});
 
If you no longer need this event, you can easily remove it using the second method called offHardwareBackButton.
$ionicPlatform.offHardwareBackButton(function() {

});
 
The last method is a bit specific; it’s used to register a hardware back button action (it can be only one action). You can use it to override an action whose priority you provide, for example, prevent a back button from closing popup.
 
$ionicPlatform.registerBackButtonAction(function(event) {

}, 100);
 
Last line number represents event priority: Return to previous view = 100 Close side menu = 150 Dismiss modal = 200 Close action sheet = 300 Dismiss popup = 400 Dismiss loading overlay = 500.
 

The First Example

 
The first example will cover the most commonly asked Ionic back button question; how to prevent back button from closing an app.
 
Amazingly, all you have to do is this:
 
.run(function($ionicPlatform, $ionicPopup) {
  // Disable BACK button on home
  $ionicPlatform.registerBackButtonAction(function(event) {
    if (true) { // your check here
      $ionicPopup.confirm({
        title: 'System warning',
        template: 'are you sure you want to exit?'
      }).then(function(res) {
        if (res) {
          ionic.Platform.exitApp();
        }
      })
    }
  }, 100);
});
 
There’s nothing special about this piece of code. We’re overriding the default “return to previous view” state, easily identifiable by number 100:
 
  }, 100);
 
On back button event, an application will pop up a warning. If you press OK application will close, or you can Cancel this action.
 
You can even go a step further and lock it only for a specific view using this check:
 
if($state.current.name=="VIEW-NAME") {

}
 
Continue Reading

  • mohamadreza

    Hi,

    thank you for your useful posts.

    I have a problem with registerBackButtonAction in my app,

    i have slide menu and tabs for example my state is : menu.tabs.home ,
    menu.tabs.favorite

    and i have som page without menu and tab for example my states is : aboutUs ,
    setting, setting.language

    i call my code about back button in .run in app.js

    my problem is:

    in tabs back button works fine and without bug but when i change state to for
    example aboutUs or setting.language back button some time works fine and some
    time not work !!!

    i am so confused:( can you help me? where is my mistake?

    Thank you 😉

  • Kim T

    Does this work with the latest version of ionic? Doesn’t seem to work for me using:
    – Ionic, v1.1.0
    – Nexus 6

    • It was made using Ionic 1.1.0, tested on Android 4.4,5.1

  • nuuleap

    this post has some great info if youre trying to go back on only one page and a regular back button on all others

  • shoaibbhimani

    Thanks 🙂

  • Vamsi

    Not at all working for me.. Should I do anything else rather than the following code? I kept it on ,run function.

    $ionicPlatform.registerBackButtonAction(function(event) {
    $ionicPopup.confirm({
    title: ‘System warning’,
    template: ‘are you sure you want to exit?’
    }).then(function(res) {
    if (res) {
    ionic.Platform.exitApp();
    }
    })
    }, 100);

    Please help me

  • razorree

    doesn’t work, looks like registering that function blocks default back functionality.

    going back stops working, you need to deliberately call $ionicHistory.goBack(); ?

    • It works just fine. Can you create a working example and I’ll check it out?

      • razorree

        works correctly only with:

        $ionicPlatform.registerBackButtonAction(function(event) {
        if (true) { // your check here
        $ionicPopup.confirm({
        title: ‘System warning’,
        template: ‘are you sure you want to exit?’
        }).then(function(res) {
        if (res) {
        ionic.Platform.exitApp();
        }
        })
        }

        // works correctly with this two lines !
        else
        $ionicHistory.goBack();

        }, 100);

  • maksm

    Good post. I recommend minor edit: In the second example if you deregister on scope $destroy you have to keep in mind, the it will stay there for cached views. You should rather handle this on ionic view events, like: $ionicView.enter and @ionicView.leave.

  • Jakub Kuchar

    $scope.$on(‘$destroy’, deregisterFirst); –> $scope.$on(‘$destroy’, deregisterFirst();) right?

  • I have the same issue. Nothing works.

  • Adil shaikh

    Can we do it with Ionic 2 ? 🙂

    • From what I have heard this functionality will be available before Ionic 2 RC1 release.

  • Marcus Vinicius Correa

    That works perfect for me… Thanks….

  • Marcus Vinicius Correa

    Do you have anything about missing back button on navigation historic on ionic app ???

  • Imaker. Amisha

    Great Code 🙂

  • hanie

    hi
    I making mp3 player with ionic. I use “cordova.plugins.backgroundMode.enable()” for play music in background if close the app.
    But when press hardware back button on Android is “stopping and closing” the app instead of just “closing and go back”.
    I tried to control with “$ionicPlatform.registerBackButtonAction” but not work.
    I tried anything but not work 🙁
    I really thank you if help me

  • vSkiper

    Great piece, you have just saved (half of) my day. Thank you 😉

  • Ulises

    Many thanks friend!!! good work for me. I try always with:

    }, 100);

    and not work, but try with:

    $ionicPlatform.registerBackButtonAction(function(e) {
    //do your stuff
    e.preventDefault();
    }, 101);

    and work perfect!!

    You are the best!!