# How to use BackButton event ? Best pratice?

**URL:** <https://forum.ionicframework.com/t/how-to-use-backbutton-event-best-pratice/3577>\
**Category:** ionic-v1\
**Created:** [April 30, 2014, 11:31am UTC](https://forum.ionicframework.com/t/how-to-use-backbutton-event-best-pratice/3577 "2014-04-30T11:31:26Z")\
**Posts on this page:** 20\
**Page:** 1

<div class="post-metadata">

**Author:** ![Maxime](https://avatars.discourse-cdn.com/v4/letter/m/a9adbd/32.png) [@Maxime](https://forum.ionicframework.com/u/Maxime)\
**Post date:** [April 30, 2014, 11:31am UTC](https://forum.ionicframework.com/t/how-to-use-backbutton-event-best-pratice/3577/1 "2014-04-30T11:31:26Z")

</div>

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

---

<div class="post-metadata">

**Author:** ![mhartington](https://sea1.discourse-cdn.com/ionicframework/user_avatar/forum.ionicframework.com/mhartington/32/137757_2.png) [@mhartington](https://forum.ionicframework.com/u/mhartington)\
**Post date:** [April 30, 2014, 7:38pm UTC](https://forum.ionicframework.com/t/how-to-use-backbutton-event-best-pratice/3577/2 "2014-04-30T19:38:06Z")

</div>

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?

---

<div class="post-metadata">

**Author:** ![Maxime](https://avatars.discourse-cdn.com/v4/letter/m/a9adbd/32.png) [@Maxime](https://forum.ionicframework.com/u/Maxime)\
**Post date:** [April 30, 2014, 9:28pm UTC](https://forum.ionicframework.com/t/how-to-use-backbutton-event-best-pratice/3577/3 "2014-04-30T21:28:06Z")

</div>

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 😉

Do you understand ? :s

---

<div class="post-metadata">

**Author:** ![mhartington](https://sea1.discourse-cdn.com/ionicframework/user_avatar/forum.ionicframework.com/mhartington/32/137757_2.png) [@mhartington](https://forum.ionicframework.com/u/mhartington)\
**Post date:** [May 1, 2014, 1:45pm UTC](https://forum.ionicframework.com/t/how-to-use-backbutton-event-best-pratice/3577/4 "2014-05-01T13:45:11Z")

</div>

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.

---

<div class="post-metadata">

**Author:** ![Maxime](https://avatars.discourse-cdn.com/v4/letter/m/a9adbd/32.png) [@Maxime](https://forum.ionicframework.com/u/Maxime)\
**Post date:** [May 2, 2014, 1:53pm UTC](https://forum.ionicframework.com/t/how-to-use-backbutton-event-best-pratice/3577/5 "2014-05-02T13:53:04Z")

</div>

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

---

<div class="post-metadata">

**Author:** ![mhartington](https://sea1.discourse-cdn.com/ionicframework/user_avatar/forum.ionicframework.com/mhartington/32/137757_2.png) [@mhartington](https://forum.ionicframework.com/u/mhartington)\
**Post date:** [May 2, 2014, 1:55pm UTC](https://forum.ionicframework.com/t/how-to-use-backbutton-event-best-pratice/3577/6 "2014-05-02T13:55:40Z")

</div>

Try adding

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

```

---

<div class="post-metadata">

**Author:** ![Maxime](https://avatars.discourse-cdn.com/v4/letter/m/a9adbd/32.png) [@Maxime](https://forum.ionicframework.com/u/Maxime)\
**Post date:** [May 2, 2014, 2:13pm UTC](https://forum.ionicframework.com/t/how-to-use-backbutton-event-best-pratice/3577/7 "2014-05-02T14:13:29Z")

</div>

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.

---

<div class="post-metadata">

**Author:** ![th3ash](https://avatars.discourse-cdn.com/v4/letter/t/da6949/32.png) [@th3ash](https://forum.ionicframework.com/u/th3ash)\
**Post date:** [May 24, 2014, 8:22am UTC](https://forum.ionicframework.com/t/how-to-use-backbutton-event-best-pratice/3577/8 "2014-05-24T08:22:17Z")

</div>

try using $state.reload();

---

<div class="post-metadata">

**Author:** ![Jana](https://avatars.discourse-cdn.com/v4/letter/j/258eb7/32.png) [@Jana](https://forum.ionicframework.com/u/Jana)\
**Post date:** [May 24, 2014, 9:57am UTC](https://forum.ionicframework.com/t/how-to-use-backbutton-event-best-pratice/3577/9 "2014-05-24T09:57:13Z")

</div>

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

})

---

<div class="post-metadata">

**Author:** ![eugi](https://avatars.discourse-cdn.com/v4/letter/e/439d5e/32.png) [@eugi](https://forum.ionicframework.com/u/eugi)\
**Post date:** [May 24, 2014, 10:42am UTC](https://forum.ionicframework.com/t/how-to-use-backbutton-event-best-pratice/3577/10 "2014-05-24T10:42:26Z")

</div>

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](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).

---

<div class="post-metadata">

**Author:** ![zwz](https://avatars.discourse-cdn.com/v4/letter/z/ecc23a/32.png) [@zwz](https://forum.ionicframework.com/u/zwz)\
**Post date:** [May 24, 2014, 10:58am UTC](https://forum.ionicframework.com/t/how-to-use-backbutton-event-best-pratice/3577/11 "2014-05-24T10:58:28Z")

</div>

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…

---

<div class="post-metadata">

**Author:** ![Xiao](https://avatars.discourse-cdn.com/v4/letter/x/2acd7d/32.png) [@Xiao](https://forum.ionicframework.com/u/Xiao)\
**Post date:** [May 27, 2014, 7:51am UTC](https://forum.ionicframework.com/t/how-to-use-backbutton-event-best-pratice/3577/12 "2014-05-27T07:51:44Z")

</div>

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…

---

<div class="post-metadata">

**Author:** ![morinted](https://avatars.discourse-cdn.com/v4/letter/m/d9b06d/32.png) [@morinted](https://forum.ionicframework.com/u/morinted)\
**Post date:** [August 5, 2014, 5:25pm UTC](https://forum.ionicframework.com/t/how-to-use-backbutton-event-best-pratice/3577/13 "2014-08-05T17:25:54Z")

</div>

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
```

---

<div class="post-metadata">

**Author:** ![striff](https://avatars.discourse-cdn.com/v4/letter/s/f1d935/32.png) [@striff](https://forum.ionicframework.com/u/striff)\
**Post date:** [November 24, 2014, 8:37pm UTC](https://forum.ionicframework.com/t/how-to-use-backbutton-event-best-pratice/3577/14 "2014-11-24T20:37:59Z")

</div>

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?

---

<div class="post-metadata">

**Author:** ![striff](https://avatars.discourse-cdn.com/v4/letter/s/f1d935/32.png) [@striff](https://forum.ionicframework.com/u/striff)\
**Post date:** [December 2, 2014, 9:57am UTC](https://forum.ionicframework.com/t/how-to-use-backbutton-event-best-pratice/3577/15 "2014-12-02T09:57:37Z")

</div>

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

---

<div class="post-metadata">

**Author:** ![Sylvain](https://avatars.discourse-cdn.com/v4/letter/s/7ba0ec/32.png) [@Sylvain](https://forum.ionicframework.com/u/Sylvain)\
**Post date:** [January 30, 2015, 10:16am UTC](https://forum.ionicframework.com/t/how-to-use-backbutton-event-best-pratice/3577/16 "2015-01-30T10:16:28Z")

</div>

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

---

<div class="post-metadata">

**Author:** ![Turbo](https://sea1.discourse-cdn.com/ionicframework/user_avatar/forum.ionicframework.com/turbo/32/73802_2.png) [@Turbo](https://forum.ionicframework.com/u/Turbo)\
**Post date:** [May 6, 2015, 1:39pm UTC](https://forum.ionicframework.com/t/how-to-use-backbutton-event-best-pratice/3577/17 "2015-05-06T13:39:56Z")

</div>

```
    //接管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

---

<div class="post-metadata">

**Author:** ![fibinacci](https://avatars.discourse-cdn.com/v4/letter/f/ec9cab/32.png) [@fibinacci](https://forum.ionicframework.com/u/fibinacci)\
**Post date:** [May 6, 2015, 4:01pm UTC](https://forum.ionicframework.com/t/how-to-use-backbutton-event-best-pratice/3577/18 "2015-05-06T16:01:34Z")

</div>

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{
????????????????????????
}
```

---

<div class="post-metadata">

**Author:** ![dhayaljaswant](https://sea1.discourse-cdn.com/ionicframework/user_avatar/forum.ionicframework.com/dhayaljaswant/32/80084_2.png) [@dhayaljaswant](https://forum.ionicframework.com/u/dhayaljaswant)\
**Post date:** [December 9, 2015, 4:51pm UTC](https://forum.ionicframework.com/t/how-to-use-backbutton-event-best-pratice/3577/19 "2015-12-09T16:51:51Z")

</div>

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

> **[Ionic Guru: Show a confirmation alert before app close](http://ionicguru.blogspot.in/2015/12/show-confirmation-alert-before-app-close.html)**
>
> xxxxx

---

<div class="post-metadata">

**Author:** ![tanjim](https://sea1.discourse-cdn.com/ionicframework/user_avatar/forum.ionicframework.com/tanjim/32/94209_2.png) [@tanjim](https://forum.ionicframework.com/u/tanjim)\
**Post date:** [January 27, 2016, 8:08am UTC](https://forum.ionicframework.com/t/how-to-use-backbutton-event-best-pratice/3577/20 "2016-01-27T08:08:49Z")

</div>

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

[Next page](https://forum.ionicframework.com/t/how-to-use-backbutton-event-best-pratice/3577.md?page=2)
