Handling hardware back button in Ionic3 Vs Ionic4

Update: This was fixed in v4.0.0-beta.8 (dfac9dc)


Related: ionic4 replacement for registerBackButtonAction


This is tracked on GitHub, in the Iconic Forum and Twitter
Until there is an official fix, you can use the workaround below.


Using platform.backButton.subscribe (see here) platform.backButton.subscribeWithPriority(0, ...) to let ionic handle closing all the modals/alerts/… , the code ionic uses when its own back button is pressed and the new router-controller together we get something like this:

import { ViewChild } from '@angular/core';
import { IonRouterOutlet, Platform } from '@ionic/angular';
import { Router } from '@angular/router';

//...

/* get a reference to the used IonRouterOutlet 
assuming this code is placed in the component
that hosts the main router outlet, probably app.components */
@ViewChild(IonRouterOutlet) routerOutlet: IonRouterOutlet;

constructor(
  ...
  /* if this is inside a page that was loaded into the router outlet,
  like the start screen of your app, you can get a reference to the 
  router outlet like this:
  @Optional() private routerOutlet: IonRouterOutlet, */
  private router: Router,
  private platform: Platform
  ...
) {
  this.platform.backButton.subscribeWithPriority(0, () => {
    if (this.routerOutlet && this.routerOutlet.canGoBack()) {
      this.routerOutlet.pop();
    } else if (this.router.url === '/LoginPage') {
      this.platform.exitApp(); 

      // or if that doesn't work, try
      navigator['app'].exitApp();
    } else {
      this.generic.showAlert("Exit", "Do you want to exit the app?", this.onYesHandler, this.onNoHandler, "backPress");
    }
  });
}

Leave a Comment