How cancel Android back button event?

I can subscribe to the back event by either
document.addEventListener('backbutton', (e) => {...})
or
Plugins.App.addListener('backButton', () => {...})

But then, how do I actually cancel the back event?
I.e. what goes into the {...}?

Following Ionic documentation Hardware back button here is sample handler that goes to the login page or exits the app.

import { IonRouterOutlet, Platform } from '@ionic/angular';
import { Plugins } from '@capacitor/core';
const { App } = Plugins;

...

constructor(
  private platform: Platform,
  private routerOutlet: IonRouterOutlet
) {
  this.platform.backButton.subscribeWithPriority(-1, () => {
   if (this.routerOutlet && this.routerOutlet.canGoBack()) {
      this.routerOutlet.pop();
    } else if (this.router.url === '/LoginPage') {
      this.platform.exitApp(); 
  });
}

The handler part will purely depend on your intention and reason for cancelling the back button action.

Thank you for your reply!

I failed to mention it in my first post, but I have also tried that as well (the JS version, as I don’t use Angular):

document.addEventListener('ionBackButton', (ev) => {
  ev.detail.register(10, () => {
    console.log('Handler was called!');
  });
});

However, the ionBackButton callback is not invoked at all.

There is also a caveat

The ionBackButton event will not be emitted when running an app in a browser or as a PWA.
For complete hardware back button support, Ionic recommends using Capacitor or Cordova.

Thanks again.
It’s a Capacitor app that I run in an emulator (should have have mentioned that from the start!), so I would expect it to work.

As I mentioned in my first post, doing
document.addEventListener('backbutton', (e) => {...})
instead does register and fire the callback, but I’m not sure if the event can be cancelled at all in that manner.

You can do something like this:

STEP1
Import platform at constructor

private platform: Platform

STEP2

const sub = this.platform.backButton.subscribeWithPriority(9999, () => {
// leave empty (the back button will become empty event
});

STEP3
When u want to enable back button, u can do like this:

if (sub) {
sub.unsubscribe();
}

Thanks, but as I mentioned in one of my earlier posts I don’t use Angular, that’s why I tried the JS-version instead.

So I just noticed that when I do
Plugins.App.addListener('backButton', () => {...})
as per the docs, it doesn’t prevent the back event the first time I go back, even though the callback is invoked. However, when I return to the page and try it second time (and every time after that), it does work.

Any ideas why it would fail only on the first visit?

Update: noticing that Plugins.App.addListener('backButton', () => {...}) works, except on the very first visit to a page that adds the listener, I managed to implement the correct back button behavior by “sprinkling” the listener across the app in the relevant places. Everything works correctly now.

A big thank you to everyone who chimed in!

1 Like

No need for plugin, you can do it with this.platform like this:

this.platform.backButton.subscribe(() => {
        if (this.router.url === '/Login') {
          this.util.presentAppExitAlert();
        } else {
          // event.preventDefault();
          console.log("invoing url ", this.router.url);
        }
      });
    });

Take a look here: https://stackoverflow.com/questions/55274992/ionic-4-prevent-disable-device-hardware-backbutton/58449967#58449967

Thanks for the tip!

I was already using that same plugin though for receiving app state events, so I didn’t need to install the plugin only for the back button functions. I simply used the additional features of the plugin.