Hardware back button with Ionic 4

not fire with “ionic serve”

I gave you the methods with a guideline page to show you where to put the bits and pieces. It’s up to you to integrate the methods. Saying it just doesn’t work means nothing.

I tried calling setupCustomBackButtonBehavior in the methods

  • constructor
  • ngOnInit
  • ionViewDidEnter

Of HOME page but none works, when press back button subscribeWithPriority method not fire

post your exact code here with code formatting using the </> button so it’s formatted pls

my code

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

  ngOnInit() {
    this.backButtonEvent(); 

    this.menuCtrl.enable(true, 'main-menu');
  }

  ionViewDidEnter(){
    this.backButtonEvent();
  }

  backButtonEvent() {
    document.addEventListener("backbutton", () => {
      alert(11);
    });
  
    this.platform.backButton.subscribe(() => { // to disable hardware back button on whole app
      alert(22);
    });
  
    try {
      this.platform.backButton.subscribeWithPriority(999999, () => { // to disable hardware back button on whole app
        alert(33);
      });
    } catch (error) {
      alert(444);
    }

  }  

comment out the other ones you’ve tried, just put the one in I gave you. It’s working for me, so it should work for you.

I already tried commenting the rest of the code and I get the same results

I don’t understand what may be happening

Hi guys,

I didn’t have any luck with all mentioned solutions, expect one, where you add event listener to js document. But this solution is not good for me, because I need to exit app conditionally, only on ‘login’ and ‘home’ routes, and back button on other pages need to behave normally ( to go back on last page in history).
So here is my solution. I made a back.button.service.ts whose variable quitOnBackButton I set conditionally to boolean value. By default it is set to false, and into components that need to be closed on backButton I set it to true in lifecycle hook ionViewWillEnter , and to false in lifecycle hook ionViewWillLeave. In app.component.ts I listen for backButton event using HostListener.

Here is code snippet:

back-button.service.ts:

import {Injectable} from '@angular/core';

@Injectable({
    providedIn: 'root'
})
export class BackButtonService {

    quitOnBackButton = false;

    closeApp() {
        (navigator as any).app.exitApp();
    }

}

login.page.ts / home.page.ts:

ionViewWillEnter() {
    this.backButtonService.quitOnBackButton = true;
  }
ionViewWillLeave() {
    this.backButtonService.quitOnBackButton = false;
  }

app.component.ts:

@HostListener('document:backbutton')
  onBackButton() {
    if (this.backButtonService.quitOnBackButton) {
      this.backButtonService.closeApp();
    } else {
      this.navCtrl.back();
    }
  }

REMEMBER

using async will not return you the exact route

update your AppComponent file

import { Component, OnInit, QueryList, ViewChildren } from '@angular/core';

import { Platform, AlertController, IonRouterOutlet } from '@ionic/angular';
import { Router} from '@angular/router';
import {Location} from '@angular/common';

@Component({
  selector: 'app-root',
  templateUrl: 'app.component.html',
  styleUrls: ['app.component.scss']
})
export class AppComponent implements OnInit {

  @ViewChildren(IonRouterOutlet) routerOutlets: QueryList < IonRouterOutlet > ;

  lastTimeBackPress = 0;
  timePeriodToExit = 2000;

  

  constructor(
    private platform: Platform,
    private alertController: AlertController,
    private router: Router,
    private location: Location
  ) {
    this.backButtonEvent();
  }


  backButtonEvent() {
    this.platform.backButton.subscribeWithPriority(0, () => {
      this.routerOutlets.forEach(async(outlet: IonRouterOutlet) => {
        if (this.router.url != '/home') {
          // await this.router.navigate(['/']);
          await this.location.back();
        } else if (this.router.url === '/home') {
          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();
  }



 
}
3 Likes

Follow This Link And u ll get solution of all in one rep.

I did this in my base component of our ionic project.

Since only android has hardware back button.

private timePeriodToExit = 2200;
private lastTimeBackPress = 0;

constructor(private tc: ToastController, private routerOutlet: IonRouterOutlet) {
if (this.platform.is("android")) {
      this.registerBackButton();
    }
}

private registerBackButton() {
  this.platform.backButton.subscribeWithPriority(-1, () => {
    if (!this.routerOutlet.canGoBack()) {
      if (
        new Date().getTime() - this.lastTimeBackPress <
        this.timePeriodToExit
      ) {
        navigator["app"].exitApp();
      } else {
        this.presentExitToast();
        this.lastTimeBackPress = new Date().getTime();
      }
    }
  });
}

async presentExitToast() {
  const toast = await this.tc.create({
    message: "Press back again to exit",
    duration: 2000,
  });
  toast.present();
}

Hope this helps someone.

This works for me!! Thanks alot!