Hi viewers, In this tutorial i will show you how to set a custom logic while clicking back button in your ionic mobile app. In my case while leaving the app i want to show some popup “Do you really want to exit app?” for this i am going to change the logic for a hardware back button.

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

Here i am importing Platform to controll my hardware backbutton logic, and App to exit the app.

subscription: any;

I am declaring a variable to store my custom logic

  private platform: Platform,
) { }

ionViewWillEnter() {
    this.subscription = this.platform.backButton.subscribeWithPriority(
      () => {

ionViewWillLeave() {

Note: we should unsubscribe our logic for the back button while leaving the page, otherwise the same logic what we written for the back button will reflect other pages

async exit() {
    const alert = await this.alertctrl.create({
      subHeader: this.translate.instant('Are you sure want to exit'),
      cssClass: 'custom-alert-class',
      buttons: [
          text: this.translate.instant('Cancel'),
          text: this.translate.instant('Exit'),
          handler: () => {
    await alert.present();

In exit() function i wrote my logic to exit my app.

Leave a Reply

Your email address will not be published. Required fields are marked *