Add to collection
Md Riyazuddin

Md Riyazuddin

Verified

How to implement hardware back button in Ionic with Capacitor

When running in a Capacitor or Cordova application, Ionic Framework will emit an ionBackButton event on the user presses the hardware back button.

When listening for the ionBackButton event, you can register a handler to be fired. This handler can perform actions such as quitting the app or opening a confirmation dialog with the help of code.

import { IonRouterOutlet, Platform } from '@ionic/angular';
import { App } from '@capacitor/app';

...

constructor(
  private platform: Platform,
  private routerOutlet: IonRouterOutlet
) {
  this.platform.backButton.subscribeWithPriority(-1, () => {
    if (!this.routerOutlet.canGoBack()) {
      App.exitApp();
    }
  });
}
Tagged with: Ionic Angular Capacitor

Comments 0

  • Sorry!! No comment posted yet. Become the first user to give comment.
Add a comment

Would you like to write for w3 sniff?

Become part of an amazing group of contributors and authors and start writing for us

Join Now
import { IonRouterOutlet, Platform } from '@ionic/angular';
import { App } from '@capacitor/app';

...

constructor(
  private platform: Platform,
  private routerOutlet: IonRouterOutlet
) {
  this.platform.backButton.subscribeWithPriority(-1, () => {
    if (!this.routerOutlet.canGoBack()) {
      App.exitApp();
    }
  });
}
Feedback submitted successfully.