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