Capacitor: How to prevent default (back navigation) on hardware back button?

Created on 1 May 2019  路  6Comments  路  Source: ionic-team/capacitor

Hi I'm able to subscribe to the backButton event via Plugins.App.addListener('backButton', function() {...}); but I can't seem to prevent the navigation from going backwards to the previous page.
Any help would be appreciated.
Thanks

Most helpful comment

What about not Ionic users then?

All 6 comments

We simply use this code to prevent the back button in case of $route.name is locked or set-pin:

App.addListener('backButton', () => {
  vm.onBackButton();
});

[...]

async onBackButton() {
  if (this.$route.name !== 'locked' && await Application.isLocked()) {
    this.$router.push({ name: 'locked' });
  } else if (this.$route.name !== 'locked' &&
      this.$route.name !== 'set-pin') {
    this.$router.go(-1);
  }
}

So it should prevent the back button, as soon as you add the listener...

I assume you're talking about android.

@MiDniGG Thanks for your response.
Yes I'm referring to Android.
So simply adding the event-listener is what does it for you?
I have that event listener and it gets triggered and it seems to prevent the default Android behavior (of exiting) but doesn't prevent the default app behavior of navigating back to previous route.

Yes, I just tried it with another route-name.
When it ends up in the (not defined) else case nothing happens.
Also tried it with a route which is not excluded, the this.$router.go(-1); is executed.

We use "vue-router": "^3.0.6" for the navigation.
Tried it with a Motorola Z2 Play - Android 8.0.0 (Hardware) and the Pixel 2 - Android 9.0 (Emulator).

Okay thanks.

So here's what I discovered:

  1. On the Capacitor (OS) level, Intercepting the android back-button and preventing it from doing the default (exiting app) can be achieved via Plugins.App.addListener('backButton', function() {...});
  2. On the Ionic/Angular (Browser) level, Intercepting the back-button and preventing it from doing the default (navigating backwards) can be achieved via adding IonicModule.forRoot({ hardwareBackButton: false }), in app.module.ts

What about not Ionic users then?

@speyou This works for me,

  App.addListener('backButton', () => {
   });
Was this page helpful?
0 / 5 - 0 ratings

Related issues

danielsogl picture danielsogl  路  3Comments

json-derulo picture json-derulo  路  3Comments

ebk46 picture ebk46  路  3Comments

peterpeterparker picture peterpeterparker  路  3Comments

gnesher picture gnesher  路  3Comments