How to use BackButton event ? Best pratice?

Hello =)
I would like to use a back button in my app but i don’t know a best pratice, where use ionicPlatform.onHardwareBackButton(callback) ? in controller, in angular.run ?

can you indicate me how to use this function =) with text or by codePen =)

Thank a lot, my app is finish, i just do implement this backbutton function =)

You can use any of the $ionicPlatfrom events in either controllers or in a run. It all depends on what you want the back button to do. Is it going to be a function just for that controller? Or is it something you want for globally?

More global. I have 4 tab on my app “Home” “Conferences” “Agenda” and “Access Plan”, and when we are on a tab, when i press Android back button, we display a popup "Do you want quit ? "

But there a page in tab, for example, in “Conferences” tab, there also “Conference detail”. When user is on " Conference detail" , back button doesn’t ask for quit and just back on previous page :wink:

Do you understand ? :s

I don’t have a android device on me right now, but you could try something like this.

.controller('TabCtrl', function($scope, $ionicPlatform) {
  $ionicPlatform.onHardwareBackButton(function() {
     e.stopPropagation();
     alert('you sure you want to exit?');
  });
})


.controller('NestedCtrl', function($scope, $ionicPlatform) {
  $ionicPlatform.onHardwareBackButton(function() {
     alert('going back now y'all');
  });
});

Then apply the TabCtrl to the main ion-tabs and the NestedCtrl to any sub pages.

it’s not work, my app come back on previous page, “e.stoppropagation()” doesn’t work :s

Try adding

event.preventDefault();
event.stopPropagation();

The same effect :s, come back on previous page
I don’t know how to use a backButton, i search since one week :s
I develop on Nexus 4.

try using $state.reload();

Try this :
(add id attribute to each ion-view)

angular.module(‘starter.controllers’, [])
.controller(‘AppCtrl’, function($scope,$ionicPlatform) {
$ionicPlatform.registerBackButtonAction(function () {
if (document.getElementById(“home”)) {
ionic.Platform.exitApp();
}
else if(document.getElementById(“fixtures”)||document.getElementById(“points”)||document.getElementById(“teams”)||document.getElementById(“winners”))
{
window.location="#/app/home";
}
else if (document.getElementById(“black”)||document.getElementById(“blue”)||document.getElementById(“orange”)||document.getElementById(“red”)||document.getElementById(“green”)||document.getElementById(“white”))
{
window.location="#/app/teams";
}
}, 100);

})

I use $ionicPlatform.registerBackButtonAction in angular.run like this:

.run(function($rootScope,$ionicPlatform,$ionicSideMenuDelegate){
  $ionicPlatform.registerBackButtonAction(function(e){
    //do your stuff
    e.preventDefault();
    return false;
  },101);
});

101 is the priority. Higher priority will be called first. Only one handler will be called. You can find other priorities here: https://github.com/driftyco/ionic/blob/master/js/angular/service/platform.js

I set it to 101 because I want to override backbutton behaviour in view history (that has priority 100).

1 Like

I have the same question with @Maxime.
I think what @Maxime means is that his 4 tabs are the root of the views, each of which has a view history. So IMO the best practice is whenever you click the backbutton, if there is no view history, just prompt to exit the app; otherwise, just go back the view history.

In this way, we may put the event handler in a run, and don’t have to write too much code or modify the code according to the invidiual views in each tab.

But this is what I just thought, I don’t if it is right or feasible…

The better way do this should use following codes…

.run(function($rootScope, $ionicPlatform, $ionicSideMenuDelegate, AlertService, $state) {
$ionicPlatform.onHardwareBackButton(function () {
    if ($state.is('#.#')) { // here to check whether the home page, if yes, exit the application
        AlertService.Confirm('System warning', 'are you sure you want to exit?',
            function() {
                navigator.app.exitApp();
            },
            function() {
                return;
            });
    }
})

})

This works well in my project, hope it help…

Reviving this in case anyone finds this thread, as it helped me solve my issue. If you’re trying to give a prompt when you don’t have any history, just use this snippet:

For me, “onHardwareBackButton” didn’t work at all.

This is in my app.run with dependency injection ‘$ionicPlatform’, ‘$ionicPopup’, and ‘$rootScope’

$ionicPlatform.registerBackButtonAction(function (e) {
            if ($rootScope.$viewHistory.backView) {
                $rootScope.$viewHistory.backView.go();
            } else {
                var confirmPopup = $ionicPopup.confirm({
                        title: 'Confirm Exit',
                        template: "Are you sure you want to close APPNAME?"
                    });
                confirmPopup.then(function (close) {
                    if (close) {
                        // there is no back view, so close the app instead
                        ionic.Platform.exitApp();
                    } // otherwise do nothing
                    console.log("User canceled exit.");
                });
            }

            e.preventDefault();
            return false;
        }, 101); // 1 more priority than back button
2 Likes

I am very lost… I don’t understand why my app won’t respond to my back button ( from the device ) to exit the app or to go back a state if it’s not home.

using this code:

angular.module('starter', ['ionic', 'starter.controllers', 'starter.services'])
    .run(function ($ionicPlatform, $state) {
        $ionicPlatform.ready(function () {
    // Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
    // for form inputs)
            if (window.cordova && window.cordova.plugins.Keyboard) {
                cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
            }
            if (window.StatusBar) {
              // org.apache.cordova.statusbar required
                StatusBar.styleDefault();
            }
  
        });
        $ionicPlatform.registerBackButtonAction(function (event) {
            if ($state.is('app.home')) {
                navigator.app.exitApp();
            } else {
                navigator.app.back();
            }
        }, 101);
    })

I also tried to have it inside the .ready but nothing worked. Can you please guide me?

Can someone help me with this? Does anyone else have this problem?
What am I doing wrong?

Do not forget to include <script src="cordova.js"></script> in your index.html file else the event will not be fired.

    //接管android默认的返回事件
    $ionicPlatform.registerBackButtonAction(function(e) {
        e.preventDefault();
        /**
         * 退出app
         */
        function showConfirm() {
            $ionicPopup.confirm({
                title: '<strong>温馨提示</strong>',
                subTitle: '<p>确定退出DuangDuang?</p>',
                okText: '退 出',
                okType: 'button-positive',
                cancelText: '取 消'
            }).then(function(res) {
                if (res) {
                    ionic.Platform.exitApp();
                } else {
                    // Don't close
                }
            });
        }

        /**
         *
         * @param title 标题
         * @param content 内容
         */
        // Is there a page to go back to?
        if ($ionicHistory.backView()) {

              $ionicHistory.goBack(-1);
        } else {
            // This is the last page: Show confirmation popup
            showConfirm();
        }
        return false;
    }, 101);

dont forget add $ionicHistory in your .run

in my project is work so i hope you can

I want to this code only one page. I do what I want this. Back key, how does the old functions in other pages

I said as

 if($ scope.is (tabs.example){

    }
else{
????????????????????????
}

If anybody facing same problem, can find full solution here:

$viewHistory.backView doesn’t work. but a little modification worked:

$ionicPlatform.registerBackButtonAction(function (e) {
  if ($ionicHistory.backView()) {
    $ionicHistory.goBack();
  } else {
    var confirmPopup = $ionicPopup.confirm({
      title: 'Confirm Exit',
      template: "Are you sure you want to exit?"
    });
    confirmPopup.then(function (close) {
      if (close) {
        // there is no back view, so close the app instead
        ionic.Platform.exitApp();
      } // otherwise do nothing
      console.log("User canceled exit.");
    });
  }

  e.preventDefault();
  return false;
}, 101);