Override Hardware back button in cordova based application - Ionic

     In a cordova based application the following three methods can be used to override hardware back button.

  • onHardwareBackButton
  • offHardwareBackButton
  • registerBackButtonAction

​onHardwareBackButton - It is used to bind a back button event, this is used to catch a back button action.

$ionicPlatform.onHardwareBackButton(function() {
  // your logic goes here.
});

offHardwareBackButton - It is used to remove the already binded back button action.

$ionicPlatform.offHardwareBackButton(function() {
  //your logic here
});

registerBackButtonAction - it’s used to register a hardware back button action. It must a single action.

$ionicPlatform.registerBackButtonAction(function() { 
  if ($location.path() === "/pageurl") {
    // you can exit the app by including the below code
    navigator.app.exitApp();
  } 
  else { 
    $ionicHistory.goBack(); 
  } 
}, 100);


If you want to register back button action in your controller then you can do this,

// run this function when either hard or soft back button is pressed 
var doUrBackButtonAction = function () { 
  //Do your stuff here.
}; 
 
// override hard back 
// registerBackButtonAction() returns a function which can be used to de-register it. 
var deregisterHardBack = $ionicPlatform.registerBackButtonAction( 
  doUrBackButtonAction, 101
 ); 
 
// cancel custom back behaviour 
$scope.$on('$destroy', function () { 
  deregisterHardBack();
});
Category: