Handling the hardware back buttons

This is really cool, how could I use it to control a side menu. When the hardware back button is pressed - open/toggle the side menu?

$ionicPlatform.registerBackButtonAction(function () {
    $ionicSideMenuDelegate.toggleLeft();
}, 100);

The code above disables the back button but dosen’t toggle the side menu, I am runnin this inside the .run function inside app.js.

Hello all ,

I am using this

$ionicPlatform.registerBackButtonAction(function () {
    $ionicSideMenuDelegate.toggleLeft();
}, 100);

to override the back button but it still looks for previous views to go !
it does get called but it doesnt override the Back Button
What could be wrong ?
Can anyone help ?

1 Like

If you end up overwriting this a lot, it get’s really clunky. Here’s a simple angular service I wrote that allows you to easily attach back button behavior to specific app states:

https://gist.github.com/kyletns/93a510465e433c1981e1

I was searching for a similar solution and seems like I finally found it. I have slightly out of context question. Where can I find documentation for “navigator.app” is it core feature of ionic? cordova? or some plugin?

There is no documentation on navigator.app for cordova, and that is on purpose.
It contains APIs and behaviour that are specific to certain platforms, and can’t/won’t be normalized accross other platforms (such as navigator.app.exitApp()).
Although I haven’t seen word on it from the core developers, I wouldn’t even count on it to be there everytime: it may not exist on the next version of cordova at all.

According to the source code, only android and amazon-fireos have that object augmented (augmentations available here for android and here for amazon-fireos).

hi sir,
i ve used this code and back button functionality works perfectly

but the popup menu wont come up if i added the “$ionicPopup.confirm” part
this is what i’ve done till now for h/w button.

$ionicPlatform.registerBackButtonAction(function (event) {
    if($state.current.name=="page1"){
	
	
	var confirmPopup = $ionicPopup.confirm({
       title: 'Consume Ice Cream',
       template: 'Are you sure you want to eat this ice cream?'
     });
     confirmPopup.then(function(res) {
       if(res) {
      navigator.app.exitApp();
       } else {
         console.log('You are not sure');
       }
     });   };
    }
else 
{ 
     navigator.app.backHistory();
    }
  }, 100);

plese help me in this case as popup functionality does not work :’(

1 Like

You should add $ionicPopup in the run parameters of your app:

angular.module('app', ['ionic', ...])
    .run(function ($ionicPlatform, $ionicPopup,...)

it work for me,
thank u

Thank you all for your code samples and suggestions. I have now implemented my own back button routing in my app.

@imesky, try using native dialog with ngCordova.

E.g.

angular.module('myApp.UI', [])
    .factory('UI', ['$cordovaToast', '$cordovaDialogs',
        function ($cordovaToast, $cordovaDialogs) {
            var self = this;
            self.toast = function (message, duration, position) {
                var msg, dur, pos;
                msg = message || '';
                dur = duration || 'short';
                pos = position || 'bottom';
                return $cordovaToast.show(msg, dur, pos);
            };
            self.alert = function (title, msg) {
                return $cordovaDialogs.alert(msg, title, 'OK');
            };
            self.confirm = function (title, msg) {
                return $cordovaDialogs.confirm(msg, title, ['Yes', 'No']);
            };
            return self;
        }
    ]);

hi bengtler,
i am testing my app via ionicView in android device,
and i am trying exactly what you but its not working.
where do you put that code?
is there any additional requirement for handling the h/w event on ionic?
can you please help me?

Please have a look at this issue http://stackoverflow.com/questions/30492011/ionic-registerbackbuttonaction-does-not-work.
I could not manage to use the registerBackButtonAction functionality provided by Ionic. I had to use the document.addEventListener(“backbutton”,…). It works like that but I don’t understand why the basic Ionic function does not work.

Any ideas?

It’s working for me but I have tested it mostly only on real devices. I tried it now also on IonicView but it’s not working as it should there so I wouldn’t trust for it. I don’t have any problems with it when installed directly on real device ionic run android

I use navigator.app.backHistory(); for back action and for exiting navigator.app.exitApp();.

I tried many many back button codes but non of then worked on real device, i tested it on samsung galaxy, moto g2 and xperia sp, Its now working at all. Anyone found working code ? BTW this is the recent code i used

.run(function($ionicPlatform){
     $ionicPlatform.registerBackButtonAction(function () {
       alert("Hello");
     }, 100);
})

Well I tested your code on my test devices and it’s working so there shouldn’t be any problems…

@k1m : Yes buddy you are right, I created new blank project and just added that code and tested in mobile, it worked. I spent many many hours to make it work, everytime i though that code is faulty. Now i realized problem is not in this code. Thanks buddy!

Ok i got the problem this morning, I found that i had defined run() method twice, I combined them together…and it worked. Thanks K1M.

Thankyou very much! -----------

@bengtler May I kiss you? :smiley: I was searching for such a functionality

2 Likes

I was trying to implement the code for registerBackButtonAction(function(){})

But I can’t seem to make it work. Pretty much what happens is that say I have the following structure:

index.html
  -- templates
    home.html
    about.html
    page1.html
        page1a.html
        page1b.html

When I navigate say, from home to page1.html to page1a.html, then navigated back to home.html and went to about.html, then press the back button, I get back to home then go all the way back to page1a.html and page1.html. Is there a more straightforward way to ensure that when you are in the home.html, the back button would not navigate back to the other pages which has been loaded previously?

Some of my code snippet (home.js)

angular.module('test.home', [])

.run(function($ionicPlatform, $ionicPopup, $state){
	$ionicPlatform.registerBackButtonAction(function(event){
		event.preventDefault();
	}, 100);
})

.config(function($stateProvider){

$stateProvider

.state('myApplication.home', {
			url: "/home",
			views:{
				'appContent' :{
					templateUrl: "template/home.html",
					controller: "HomeCtrl"
				}
			}
		})
	})

.controller('HomeCtrl', function($scope, $ionicPlatform, $ionicModal){
	// Some codes here...
});

I’m quite new to Ionic so pardon if some of my codes does not make sense (still trying to grasp the routing and everything in between).

Slightly Off-Topic:

Just wondering, if you are using the Chrome Debugger and using the emulator for the application, is the browser back button the same as the back button for the hardware (Android device)? Or would it still be preferable to generate an APK and load it to your device and test?

Question, what’s the outcome you were expecting?

Because back button in your case behaves just as it should.

P.S. Please open a new topic for this question