Hello!
I’ve already looked for it in the forum without any luck.
Has any of you been able to find a way for disabling the hardware back button or to link other events to it?
With Ionic 3 it worked like a charm but with Ionic 5 (and even Ionic 4) i’m not able to lock it.
Thanks!
1 Like
You can subscribe to the BackButton like:
this.platform.backButton.subscribeWithPriority(priority, () => {
// do on back button click
});
Information about the Priority Handling can be found here.
Just doing nothing inside will kinda disable it.
1 Like
it did not stop modal dismissing nor page popping. Basically, the Hardware Back button behaviour is not overriden
1 Like
Maybe this can be helpful here as well (the code is also pasted below here): Disable back button on some of the views in ionic 4 - #5 by peterprmedia
I believe that you need to handle the subscription for the backButton inside the constructor method of your view class where you want to manipulate the normal actions of the hardware back button.
Also: If you only need the manipulation of the back button to be on the current view and not child views, then letting a boolean that’s affected by ionDidEnter and ionWillLeave might help distinguishing when we want to manipulate.
private isCurrentView: boolean;
private displayWarning: boolean;
constructor(private platform: Platform) {
this.subscriptions.add(
this.platform.backButton.subscribeWithPriority(9999, (processNextHandler) => {
if (this.isCurrentView) {
this.displayWarning = true;
// Or other stuff that you want to do to warn the user.
} else {
processNextHandler();
}
})
}
ionViewDidEnter() {
this.isCurrentView = true;
}
ionViewWillLeave() {
this.isCurrentView = false;
}
The priority of 9999 should make your code come first in the priority before the original actions, referring to what @EinfachHans mentioned earlier. And if you don’t want to stop all other actions from happening afterwards, then remember to add the processNextHandler parameter to the subscription and execute that method.
async backButtonEvent() {
this.platform.backButton.subscribeWithPriority(9999, () => {
this.modalCtrl.getTop().then( modal => {
if ( modal != null ) { return; } // Don't go back if there's a modal opened
this.onBackButton();
});
});
}
onBackButton() {
this.routerOutlets.forEach(async(outlet: IonRouterOutlet) => {
// tslint:disable-next-line:triple-equals
if (this.router.url != '/dashboard') {
await this.location.back();
} else if (this.router.url === '/dashboard') {
if (new Date().getTime() - this.lastTimeBackPress >= this.timePeriodToExit) {
this.lastTimeBackPress = new Date().getTime();
this.presentAlertConfirm();
} else {
navigator['app'].exitApp();
}
}
});
}