My Hardware 'Back Button Action' is not working in Ionic 4

Try This:

lastTimeBackPress = 0;
timePeriodToExit = 2000;
@ViewChildren(IonRouterOutlet) routerOutlets: QueryList < IonRouterOutlet > ;
backButtonEvent() {
  document.addEventListener("backbutton", async() => {
    try {
      const element = await this.modalCtrl.getTop();
      if (element) {
        element.dismiss();
        return;
      }
    } catch (error) {
      console.log(error);
    }
    this.routerOutlets.forEach(async(outlet: IonRouterOutlet) => {
      if (this.router.url != '/tabs/tab1') {
        await this.router.navigate(['/tabs/tab1']);
      } else if (this.router.url === '/tabs/tab1') {
        if (new Date().getTime() - this.lastTimeBackPress >= this.timePeriodToExit) {
          await this.presentAlertConfirm();
          this.lastTimeBackPress = new Date().getTime();
        }
        navigator['app'].exitApp(); // work for ionic 4
      }
    });
  });
}

And call this function in the constructor. This solved my problem because I am using the tabs theme and outlet.pop(); was not working. So I tried this method.


Do it this Way.

constructor(private platform: Platform) {
  this.platform.backButton.subscribe(() => {

  });
}

In response to @Raghav comment, I would try it like this:

lastTimeBackPress = 0;
timePeriodToExit = 2000;
@ViewChildren(IonRouterOutlet) routerOutlets: QueryList < IonRouterOutlet > ;

constructor(private platform: Platform) {
  this.backButtonEvent();
}

backButtonEvent() {
  this.platform.backButton.subscribeWithPriority(0, () => {
    this.routerOutlets.forEach(async(outlet: IonRouterOutlet) => {
      if (this.router.url != '/tabs/tab1') {
        await this.router.navigate(['/tabs/tab1']);
      } else if (this.router.url === '/tabs/tab1') {
        if (new Date().getTime() - this.lastTimeBackPress >= this.timePeriodToExit) {
          this.lastTimeBackPress = new Date().getTime();
          this.presentAlertConfirm();
        } else {
          navigator['app'].exitApp();
        }
      }
    });
  });
}

async presentAlertConfirm() {
  const alert = await this.alertController.create({
    // header: 'Confirm!',
    message: 'Are you sure you want to exit the app?',
    buttons: [{
      text: 'Cancel',
      role: 'cancel',
      cssClass: 'secondary',
      handler: (blah) => {}
    }, {
      text: 'Close App',
      handler: () => {
        navigator['app'].exitApp();
      }
    }]
  });

  await alert.present();
}