Hardware back button with Ionic 4

Hi,

to prevent navigating back to login page i simply set the root navigation at login:

 //Check if user is logged-in; if so the dashboard will be loaded otherwise the login-page
            this.authenticationService.authenticationState.subscribe(state => {
                if (state) {
                    this.navController.navigateRoot(['menu/tabs/dashboard']);
                } else {
                    this.navController.navigateRoot('login')
                }
            });

By setting the root there is no possibility to navigate back to another page.

import { App} from ‘ionic-angular’;

constructor(private app: App) {

this.backbutton()

}

backbutton() {

this.platform.ready().then(() => {

  //Registration of push in Android and Windows Phone
  this.platform.registerBackButtonAction(() => {
   let nav = this.app.getActiveNav();
    if (nav.canGoBack()){ //Can we go back?
     nav.pop();
   

    }else{
      
      
     
      this.navCtrl.pop()
      
     
    }
  });
});

}

How is it possible to use the hardware back button to navigate through tabs?

import { Component, OnInit, ViewEncapsulation, ViewChildren, QueryList } from '@angular/core';
import { Events, MenuController, Platform, IonRouterOutlet, ActionSheetController, PopoverController, ModalController } from '@ionic/angular';
import { Toast } from '@ionic-native/toast/ngx';

export class AppComponent implements OnInit {

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

  lastTimeBackPress = 0;
    timePeriodToExit = 2000;
constructor(
    private menu: MenuController,
    private platform: Platform,
    private router: Router,
    private push: Push,
    public toastCtrl: ToastController,
    private actionSheetCtrl: ActionSheetController,
    private popoverCtrl: PopoverController,
    public modalCtrl: ModalController,
    private toast: Toast
  ) {    
    this.backButtonEvent();
  }
backButtonEvent() {
    this.platform.backButton.subscribe(async () => {
        // close action sheet
        try {
            const element = await this.actionSheetCtrl.getTop();
            if (element) {
                element.dismiss();
                return;
            }
        } catch (error) {
        }

        // close popover
        try {
            const element = await this.popoverCtrl.getTop();
            if (element) {
                element.dismiss();
                return;
            }
        } catch (error) {
        }

        // close modal
        try {
            const element = await this.modalCtrl.getTop();
            if (element) {
                element.dismiss();
                return;
            }
        } catch (error) {
            console.log(error);

        }

        // close side menua
        try {
            const element = await this.menu.getOpen();
            if (element !== null) {
                this.menu.close();
                return;

            }

        } catch (error) {

        }

        this.routerOutlets.forEach((outlet: IonRouterOutlet) => {
            if (outlet && outlet.canGoBack()) {
                outlet.pop();

            } else if (this.router.url === '/login') {
                if (new Date().getTime() - this.lastTimeBackPress < this.timePeriodToExit) {
                    // this.platform.exitApp(); // Exit from app
                    navigator['app'].exitApp(); // work for ionic 4

                } else {
                    this.toast.show(
                        `Press back again to exit App.`,
                        '2000',
                        'center')
                        .subscribe(toast => {
                            // console.log(JSON.stringify(toast));
                        });
                    this.lastTimeBackPress = new Date().getTime();
                }
            }
        });
    });
}

It works for me and I think it will help you too. If it works give a heart. Thanks.

1 Like
import { Platform } from '@ionic/angular';
import { AppMinimize } from '@ionic-native/app-minimize/ngx';
....// blah blah
constructor( private platform: Platform,private appMinimize: AppMinimize) {
            this.platform.backButton.subscribe(()=>{
                // navigator['app'].exitApp();
                this.appMinimize.minimize();
            });
    }
....// blah blah

Try the above code… Its working for me perfectly as the android home button works

Easy code that I use in my app.component:

private setAndroidBackButtonBehavior(deviceInfo: DeviceInfo): void {
    if (deviceInfo.platform == "android") {
      this.platform.backButton.subscribe(() => {
        if (window.location.pathname == "/home") {
          navigator['app'].exitApp();
        }
      });
    }
  }

Thanks, Its working…
registerBackButtonAction this function no more exist in platform.

Does this work for IOS as well?

iOS doesn’t have a hardware back button. Only Android.

But navigator[‘app’].exitApp() works anywhere

All of this solutions are not working for me.
Back button minimise app only when I click it for the first time, as soon as I navigate to other page and go back to my homePage, app is not minimised any more. Im using “@angular/router”: “8.2.2”, “@ionic/angular”: “4.7.4”, “@ionic-native/app-minimize”: “5.12.0”,

This solution works from version ionic/angular 4.7.2 https://github.com/ionic-team/ionic/releases/tag/v4.7.2
I was on 4.6.1 and no events were firing

you to write a method for exitapp() pop up to terminate app

  this.subscribe = this.platform.backButton.subscribeWithPriority(666666,()=>{
      if(this.constructor.name == "your page name"){
        if(window.confirm("do you want to exit app"))
        {navigator["app"].exitApp();}
      }
    })

Does this work in production?

can’t get you!? what do you mean by production ?

When you build with the -prod flag, causing the minimizer to run, any code that relies on class names as strings tends to break. I was wondering if this idiom of yours is immune to this problem in your experience.

not working in my case,

Hi,
after registering this event, is it possible to unregister the same event?

Thank you

cld

Thank you so much , Worked like charm

None of the following options work for me in Ionic 4 with android browser (not android APK).

Did anyone find a way to make it work?

document.addEventListener("backbutton", () => {
      alert(11);
    });
  
    this.platform.backButton.subscribe(() => {
      alert(22);
    });
  
    this.platform.backButton.subscribeWithPriority(0, () => { 
      alert(33);
    });
import { Component, OnInit } from '@angular/core';
import {  Platform } from '@ionic/angular';


@Component({
  selector: 'app-somePage',
  templateUrl: './somePage.page.html',
  styleUrls: ['./somePage.page.scss']
})
export class SomePage implements OnInit {

  public customBackButton: any;


  constructor(
      public _Platform: Platform
    //....
  ) { 
  }

  ngOnInit() {
  }  
  
  setupCustomBackButtonBehaviour() {
    try {
      this.customBackButton = this._Platform.backButton.subscribeWithPriority(999999, () => {
        // do something...
      });  
    }
    catch(e) {
      // crap
    }
  }

  removeCustomBackButtonBehaviour() {
    try {
      this.customBackButton.unsubscribe();
    }
    catch(e) {
      // console.log(e)
    }
  }
}