Hardware back button with Ionic 4

@joseadrian I found out that the problem was already reported, see https://github.com/ionic-team/ionic/issues/14803

I guess you could close the issue you opened because https://github.com/ionic-team/ionic/issues/14803 was added to the team’s backlog for the core

any workaround right now?

no, no workaround except waiting for a solution in a next beta release

@webpunks @reedrichards @joseadrian @MustafaLokhandwala

Theby peer review confirmed working workaround … is available …

Here: https://stackoverflow.com/a/51729093

Also, greetings from SO

Yep forgot to post again about this, adding a custom back would work

Works for me as well, but just outside of the tabs page? How to maintain the navigation stack in app.component as well as in the tabs page?

Example for Hardware back button with ionic 4:


export class AppComponent {

    // set up hardware back button event.
    lastTimeBackPress = 0;
    timePeriodToExit = 2000;

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

    constructor(
        private platform: Platform,
        private splashScreen: SplashScreen,
        private statusBar: StatusBar,
        public modalCtrl: ModalController,
        private menu: MenuController,
        private actionSheetCtrl: ActionSheetController,
        private popoverCtrl: PopoverController,
        private router: Router,
        private toast: Toast) {
        this.initializeApp();
        // Initialize BackButton Eevent.
        this.backButtonEvent();
    }


// active hardware back button
    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 === '/home') {
                    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’s work for me.

7 Likes

Hello,
Thank you for the code it works perfectly but can i disable for a particular page.

2 Likes

I think in v4.beta.11, for a big part, the hardware back should work without any workaround

Really thanks, works perfectly!
Except by the Toast (I had to change it from Toast to ToastController because the module /ngx are not present on @ionic-native/toast/ plugin so I can’t subscribe to it.)

1 Like

Yes, You can, just create and add the constant back button to your conditional ‘if’.
Replace “/route 1”, “/route 2”, (add how many you need) . with the routes where wanna to disable the back button.

            this.routerOutlets.forEach((outlet: IonRouterOutlet) => {
                const back_button_off = [ '/route1', '/route2' ];
                
                if (outlet && outlet.canGoBack() && !back_button_off.includes(this.router.url)) {
                    outlet.pop();

Hi, I am getting the below exception in beta ionic 4:

ERROR in src/app/app.component.ts(22,20): error TS2304: Cannot find name ‘IonRouterOutlet’.
src/app/app.component.ts(22,52): error TS2304: Cannot find name ‘QueryList’.
src/app/app.component.ts(22,62): error TS2304: Cannot find name ‘IonRouterOutlet’.
src/app/app.component.ts(110,49): error TS2304: Cannot find name ‘IonRouterOutlet’.

Could you please someone help me ?

add this app.component.ts:

import {  ViewChildren, QueryList } from '@angular/core';
import { IonRouterOutlet } from '@ionic/angular';

@Component({
    selector: 'app-root',
    templateUrl: 'app.component.html'
})
export class AppComponent {

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

    constructor() {}

it’s work for me.
thanks.

Hi all, just gonna let a not again, in Ionic v4-beta.11 or beta.12 the hardware back button just works fine out of the box respectively no need of any extra particular code

I’m on Ionic V4.0.0-beta.12 and it doesn’t work.
Does this solution only work at a hybrid app which has cordova and doesn’t work at a PWA?

Same here. PWA. beta.13. No event fired:

constructor(public navParams: NavParams, public modalCtrl: ModalController, public platform: Platform) { 
    this.platform.backButton.subscribe(() => {
      console.log("TEST");
    });
}

I upload testcode to github:

1 Like

@cherzog has the actual solution - using subscription. I’ve just tested it. The v4 documents just haven’t been updated / were copied and pasted from v3.

I’m confused. My solution works for you? Without using Cordova? It does not work for me. Not even with the last beta (15). Neither in the browser, nor on the smartphone. There are backlog items on Github:

ionic info

Ionic:

   ionic (Ionic CLI)             : 4.3.1
   Ionic Framework               : @ionic/angular 4.0.0-beta.15
   @angular-devkit/build-angular : 0.8.6
   @angular-devkit/schematics    : 0.8.6
   @angular/cli                  : 6.2.6
   @ionic/angular-toolkit        : 1.1.0

System:

   NodeJS : v8.11.2 (C:\Program Files (x86)\nodejs\node.exe)
   npm    : 6.4.1
   OS     : Windows 10