Handling the Android back button

I’m struggling to understand how to use the Hardware Back button handlers in Ionic 5.

In my app I have the following structure:

Main Menu - List Component - Detail Component

If I navigate to the List Component and open up the Detail Component for item A, return to the list (via the Ionic back button), then do the same for Item B and then for Item C and so on. When I return to the List Component and I then hit the Android Hardware Back button I would like to always return to the Menu page immediately regardless if whether I have opened up any detail items or not but at the moment my app takes me back into every detail page I have opened previously and back to the list page again before finally returning to the menu at the end of that process.

What is the correct way of handling this and overriding that Back button press when in the List Component? Does a handler need to be added to that List Component that overrides the operation of the back button somehow and with a higher priority that the one I already have at the top level? And do I need to unsubscribe from it when the list component is destroyed?

It would be useful to see some code on how you’re navigating between your pages.

I have implemented several back button overrides in apps that force specific navigation, based on the ‘current’ page being navigated from, so it sounds similar to what you need.

e.g.

        this.platform.backButton.subscribeWithPriority(999, () => {
            var currentUrl = window.location.href;

            var toLoginPages = [
                'reset-password/step-1',
                'forgot-username'
            ];
                      
           if (toLoginPages.some(x => currentUrl.indexOf(x) > -1)) {
                this.nav.navigateRoot('/login');
            }
        });

Anyway, I’d be hesitant to suggest that approach until we rule out that you’re not navigating in an odd/unusual way first.

1 Like

@Daveshirman thanks for that - just as you were replying I was discovering that the fault was in my top level back button handler and I don’t need the additional handlers at all.

1 Like