I’m currently trying to setup a custom hardware back button function for my app through Android Devices. My current setup includes a Home Page -> Page 1 -> Page 2 -> Page 3. What I’d like to have happen is when the user is currently on Page 3 and hits the hardware back button on an Android device, the user is then sent back to the home page every time.
I have the following code setup in my app.component.ts, but I’m not sure what to put in the (???) spot to force the hardware back button to send the user to the homepage:
this.platform.backButton.subscribe(() => {
if (this.router.url === '/page-3') {
???
//magic code that sends the user back to the home page
} else if (this.routerOutlet && this.routerOutlet.canGoBack()) {
this.routerOutlet.pop();
}
Anyone have any thoughts into what I should be looking into? I’ve looked into Navigation Controllers, Routers, Router Outlets, Guards but haven’t found a definitive answer to my problem. Any help would be greatly appreciated. Thanks.
I tried each of those lines individually and the Android Hardware back button in the emulator kicked me back to page 2 from page 3 every time instead of sending me back to the home page. Is there some code that I’m unaware of that didn’t appear in any of my Google searches that I should be using instead?
this.platform.backButton.subscribe(() => {
if (this.router.url === '/page-3') {
this.testAlert("Test this.routerOutlet.pop(3);");
} else if (this.routerOutlet && this.routerOutlet.canGoBack()) {
//this.testAlert("Test regular back button click");
this.routerOutlet.pop();
}
});
async testAlert(text){
const alert = await this.alertCtrl.create({
header: 'Correct Page',
message: 'I am on the /page-3 page. '+text,
});
await alert.present();
}
The top alert appears every time I go back from page 3. The bottom alert (when it’s not commented out) appears every time I hit the hardware back button.