Press back button again to exit

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.

14 Likes

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);

})
11 Likes

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

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

Thank u very
Above code working fine

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

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?

Its working fine :slight_smile: :ok_hand:

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

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

Hope this works for you… :slight_smile:

3 Likes

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
};

};

`

1 Like

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

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);
    }
  }

1 Like

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

Ionic 3

 platform.ready().then(() => {
            // Okay, so the platform is ready and our plugins are available.
            // Here you can do any higher level native things you might need.
            statusBar.styleDefault();
            splashScreen.hide();
            this.appInicialize();
            platform.registerBackButtonAction(() => {
                if (this.alertShown==false) {
                    this.presentConfirm();
                }
            }, 0)
        });
    }

  
   //Function ask confirmation for exit app
    presentConfirm() {
        let alert = this.alertCtrl.create({
            title: 'Sair do aplicativo',
            message: 'Deseja mesmo sair do aplicativo?',
            buttons: [
                {
                    text: 'Sim',
                    handler: () => {
                        console.log('Yes clicked');
                        this.platform.exitApp();
                    }
                },
                {
                    text: 'Cancelar',
                    role: 'cancel',
                    handler: () => {
                        console.log('Cancel clicked');
                        this.alertShown=false;
                    }
                }
            ]
        });
        alert.present().then(()=>{
            this.alertShown=true;
        });
    }