I\'m trying to disable the back button on my Cordova app. I\'m using AngularJS + Ionic Framework. I found topics about this and tried the code bellow, but it has absolutely
$ionicPlatform.registerBackButtonAction(function (event) {
event.preventDefault();
}, 100);
this will prevent back button functionality.
For Ionic 3:
// root component
export class MyApp {
constructor(platform: Platform) {
platform.ready().then(() => {
platform.registerBackButtonAction(() => {
this.customBackButtonHandler();
}, 100)
});
}
customBackButtonHandler() {
...
}
}
To expand upon David D's answer I have included the go back implementation.
Put this in your applications .run
function:
$ionicPlatform.registerBackButtonAction(function (event) {
if ($ionicHistory.currentStateName() === 'someStateName'){
event.preventDefault();
} else {
$ionicHistory.goBack();
}
}, 100);
This will not work in controllers, it is application wide.
Its simple trick prevent go back to single page:
`.controller('DashCtrl', function($scope,$ionicHistory) {
$ionicHistory.clearCache();
$ionicHistory.clearHistory();
})`
To disable hardware back button in Ionic application for controller (or controller of component), you can make the following workaround, but first it is actually not for controller itself, but it combination between controllers and state, in your controller, add your normal code:
var deRegisterHardBack = $ionicPlatform.registerBackButtonAction(
function (event) {
if (youConditionHere) {
event.preventDefault();
// do something
} else {
$ionicHistory.goBack();
}
}, 100);
But in your $stateProvider
add disableHardwareBackButton
like the following:
$stateProvider
.state('app.stateB', {
url: '/page-b/:id',
template: '<ion-view><ion-nav-title>Sub Page </ion-nav-title>Hello</ion-view>',
disableHardwareBackButton : true
});
Inside your module('app').run function:
$ionicPlatform.registerBackButtonAction(function(event){
if ($state.current.disableHardwareBackButton){
event.preventDefault();
} else {
$ionicHistory.goBack();
}
}
In this way you get around the issue with "sub section" or "inside controller"
To prevent App from device back button functionality use,
$ionicPlatform.registerBackButtonAction(function (event) {
event.preventDefault();
}, 100);
If you want to prevent the particular page use,
$ionicPlatform.registerBackButtonAction(function (event) {
event.preventDefault();
if ($location.path() === "/pagename" || $location.path() === "pagename") {
navigator.app.exitApp();
} else {
$ionicHistory.goBack();
}
}, 100);