Warning: Before we go any further I want to make one thing clear. This tutorial is made explicitly for the Ionic framework version 1. If you came here looking for a tutorial for what is now known as Ionic Framework (Ionic 2|3) you may find it here.
 
In this guide, I’m going to walk you through the process of handling Android hardware back-button.
 
The main problem of a hardware back-button is usually a bad timing. From time to time, application end users will unintentionally trigger a back-button event. Unless properly configured, this deed may trigger several unwanted actions, for example, application termination.
 
We can all agree that this may ruin an application usability.
 
I will show you how we can use Ionic registerBackButtonAction function to get a full control over back-button triggering, just like a pro.
 
In the end, you will be able to do these:
 
  • Prevent back-button from terminating an app
  • Prevent multiple triggering of registerBackButtonAction function
  • Prevent back-button on a specific action (for example popup termination)
 
 

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

 
The Ionic framework provides a set of utility methods you can use to affect the underlying device. These functions can retrieve the “device ready” state, various device oriented information, platform data, etc.
 
For this example we will use $ionicPlatform which is an AngularJS abstraction of ionic.Platform. You can use it to detect the current platform, or, what’s more important for us now, override the Android back button.
 
$ionicPlatform provides these three functions:
 
  • onHardwareBackButton
  • offHardwareBackButton
  • registerBackButtonAction
 
FunctiononHardwareBackButton is used to handle a back-button event. Essentially, we will use this method to hijack back-button event.
 
An uncomplicated code example looks like this:
 
$ionicPlatform.onHardwareBackButton(function() {

});
 
As this function creates a new event, if we no longer need it, we can easily eliminate it using this function:
 
$ionicPlatform.offHardwareBackButton(function() {

});
 
The last function is a little bit specific. We can use it to register a new hardware back-button action (it can be only one action). With it, we can override any action using provided priority. For example, prevent a back button from closing popup:
 
$ionicPlatform.registerBackButtonAction(function(event) {

}, 100);
 
In above example, the last line number represents event priority.
 
Several levels of priorities exist:
 
  • Return to the previous view = 100
  • Close side menu = 150
  • Dismiss modal = 200
  • Close action sheet = 300
  • Dismiss popup = 400
  • Dismiss loading overlay = 500
 

The First Example

 
This example will cover the most commonly found Ionic back-button problem; how to prevent back button from application termination.
 
Amazingly, this is all you have to do:
 
.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);
});
 
In this example, we’re overriding the default “return to the previous view” state, easily identifiable by number 100:
 
  }, 100);
 
During back-button event, an application will create a popup warning. An application will terminate on OK, or stop an action on Cancel.
 
We can even go a step further and lock it to a specific view:
 
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?

    • Firoze Rakib

      no that would be
      $scope.$on(‘$destroy’, function() {
      deregisterFirst();
      });

      when you do $scope.$on(‘$destroy’, deregisterFirst); you are passing the function directly to the handler to be invoked
      but if you do $scope.$on(‘$destroy’, deregisterFirst()); you are only passing the return value of deregisterFirst() whatever that value may be

      • Jakub Kuchar

        true

  • 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!!

  • Brayan LP

    excelente man, tenia dudas de como bloquear el boton y me las solucionaste

  • Modesto Barreto

    Dear Dragan Gaić. I’m sorry for my English, I’m a beginner in ionic and I have this problem. In which folder do I put this code?