menu

Handle hardware back button in Ionic.

  • date_range 22/08/2015 00:00 info
    sort label

Create a service in ionic with the following javascript code:

  this.deregister = undefined;
    this.disable = function () {
      this.deregister = $ionicPlatform.registerBackButtonAction(function (e) {
        e.preventDefault();
        return false;
      }, 101);

    }
    this.enable = function () {
      if (this.deregister !== undefined) {
        this.deregister();
        this.deregister = undefined;
      }
    }

Inside app.js inside .run function write a function which gets call when we click on hardware back button.


1:  $ionicPlatform.onHardwareBackButton(function () {
2:        console.log("Event " + JSON.stringify());
3:        if (true) {
5:          $ionicPopup.confirm({
6:            template: 'template for pop up'
7:          }).then(function (res) {
8:            if (res) {
9:              navigator.app.exitApp();
10:            }
11:          })
12:        }
13:      });

Now inside your controller where you want to disable the back button, inject the service and call its disable method as follow.


1:   HardwareBackButtonManager.disable();