Press back button again to exit


#1

This code snippet shows a toast notification to make sure user really want to close the app.
It override the default behaviour of Ionic to exit the app when the user press the back button and she/he is at the beginning of view history.
Instead, a toast message with text “Press back button again to exit” is shown, and if the user press back again in 2 seconds (configurable), app will close, otherwise nothing happen.
I use this Toast Plugin, but any other similar plugin should work.
Here is the code:

.run(function($rootScope,$ionicPlatform){
  $ionicPlatform.registerBackButtonAction(function(e){
    if ($rootScope.backButtonPressedOnceToExit) {
      ionic.Platform.exitApp();
    }
    else if ($rootScope.$viewHistory.backView) {
      $rootScope.$viewHistory.backView.go();
    }
    else {
      $rootScope.backButtonPressedOnceToExit = true;
      window.plugins.toast.showShortCenter(
        "Press back button again to exit",function(a){},function(b){}
      );
      setTimeout(function(){
        $rootScope.backButtonPressedOnceToExit = false;
      },2000);
    }
    e.preventDefault();
    return false;
  },101);

});

I didn’t test it extensively, but for now it works well in my app.


How to hold back twice to exit
How can I show a exit app confirm when on login or home page?
#2

Here is a minor tweak to make it work with the latest beta 14

.run(function($rootScope, $ionicPlatform, $ionicHistory){
  $ionicPlatform.registerBackButtonAction(function(e){
    if ($rootScope.backButtonPressedOnceToExit) {
      ionic.Platform.exitApp();
    }

    else if ($ionicHistory.backView()) {
      $ionicHistory.goBack();
    }
    else {
      $rootScope.backButtonPressedOnceToExit = true;
      window.plugins.toast.showShortCenter(
        "Press back button again to exit",function(a){},function(b){}
      );
      setTimeout(function(){
        $rootScope.backButtonPressedOnceToExit = false;
      },2000);
    }
    e.preventDefault();
    return false;
  },101);

})

#3

But for me $ionicPlatform.registerBackButtonAction is not working in my mobile app i am calling this function in my app.js please suggest me how to do it


#4

use chrome://inspect and look for errors on console


#5

Thank u very
Above code working fine


#6

Thanks, this one works. The original function broke the back button completely…


#7

Hi,

This code doesn’t work for me.

I get the error:

Uncaught TypeError: Cannot read property 'backView' of undefined 

I did include $rootScope, $ionicPlatform, $ionicHistory.
And I put it in the $ionicPlatform.ready.

Any help, please?


#8

Its working fine :slight_smile: :ok_hand:


#9

How work if i want not save history and cache a specific view, and if push back button in this view exit app


#10
           //Do on hard back pressed in android
           $ionicPlatform.onHardwareBackButton(function(){
             
                 //Exit app
                 ionic.Platform.exitApp();
             });
          }

Hope this works for you… :slight_smile:


#11

yes i solved this way,

`angular.module(‘historialApp’, [‘ionic’])
.controller(‘borrarHistorial’, borrarHistorial)
.factory(‘salirApp’, salirApp);

borrarHistorial.$inject = [’$ionicHistory’, ‘salirApp’];

function borrarHistorial($ionicHistory, salirApp){

salirApp.salida();    
$ionicHistory.clearHistory();   

};

salirApp.$inject = [’$ionicPlatform’,’$ionicHistory’, ‘$timeout’];

function salirApp ($ionicPlatform , $ionicHistory, $timeout) {

function salida(){
    
    var BackButton = 0;
    
    $ionicPlatform.registerBackButtonAction(function () {
        
        if ($ionicHistory.currentStateName() == 'menuestu' || $ionicHistory.currentStateName() == 'menuprof') {
            
            if (BackButton == 0) {
                
                BackButton++;
                window.plugins.toast.showLongCenter('Presione nuevamente para salir');
                
                $timeout(function() {
                    BackButton = 0;
                }, 2500);
                
            }else{
                navigator.app.exitApp();
            }
            
        }else{
            $ionicHistory.backView();
        }
        
    }, 100);
    
}

return {
    salida: salida
};

};

`


#12

Thanks, this one works. The original function broke the back button completely.


#13

Ha!! This is part of my production code in app.component.js file. However it does not work consistently in production mode. -_-!!

  registerBackButtonAction() {
    this.platform.registerBackButtonAction((): any => {

      // if there is an alert
      let el: any = document.querySelector('ion-backdrop');
      if (el) {
        el.click();
        return;
      }

      // if there are tabs
      let page = this.navCtrl.getActive().instance;
      if (!(page instanceof TabsPage)) {
        if (!this.navCtrl.canGoBack()) {
          return this.showExit();
        }
        return this.navCtrl.pop();
      }
      let tabs = page.tabs;
      let activeNav = tabs.getSelected();
      if (!activeNav.canGoBack()) {

        // if not on a specific tab, nav to that tab
        if (activeNav.getActive().name !== 'PatientListPage') {
          return this.tabs.select(0);
        } else {
          return this.showExit();
        }
      }
      return activeNav.pop();

      // refer this priority number from this link:
      // http://www.gajotres.net/ionic-framework-handling-android-back-button-like-a-pro/
    }, 101);
  }

  // exit toast
  showExit() {
    if (this.backButtonPressed) {
      this.platform.exitApp();
    } else {
      this.toastCtrl.present('Press again to exit App');
      this.backButtonPressed = true;
      if (this.backButtonPressedTimer) {
        clearTimeout(this.backButtonPressedTimer);
      }
      this.backButtonPressedTimer = setTimeout(() => {
        this.backButtonPressed = false
      }, 2000);
    }
  }


#14

now i need to know that, how to restrict the ‘back’ on the specified state(‘app.home’) which is redirected after the login.