Ionic 2 overwrite back button function my way

I guess that most of APP developers would not prefer a crude exit of their APP when back button was pressed, and as you may already know using ionic you can register a callback on the back button pressed event. That is pretty straight forward, but what comes in the registered callback is most a matter of preference, but nevertheless, this method that I lately used works on the newest 3.1.1 Ionic version.
I will explain in just in 2 phrases, what is the expected behaviour:
The first thing that it will do it will look if there is an overlay view/component active like a Modal, Toast, Alert and if there is it will dismiss that component.
Then it will check if a menu is opened, if it is it will close it, then it will check if the keyboard is opened, and close it in case previous was true, and lastly it will check if you can go back taking into account the current page, and if you can’t it will present a confirmation alert to exit the app.
Here is the code:

this.platform.registerBackButtonAction(() => {

    let activePortal = this.app._appRoot._loadingPortal.getActive() ||
        this.app._appRoot._modalPortal.getActive() ||
        this.app._appRoot._toastPortal.getActive() ||
        this.app._appRoot._overlayPortal.getActive();

    if (activePortal) {
        activePortal.dismiss();
        return
    } else if (this.menu.isOpen()) {

        this.menu.close();

    } else if (this.keyboard.isOpen()) {
        this.keyboard.close();
        return;
    }
    else {
        if (this.nav.canGoBack()) {
            this.nav.pop();
        } else {

            let alert = this.alertCtrl.create({
                title: 'Ieșire',
                message: 'Vrei sa ieși din aplicație?',
                buttons: [
                    {
                        text: 'Da',
                        handler: () => {
                            this.platform.exitApp();
                        }
                    },
                    {
                        text: 'Nu',
                        role: 'cancel',
                        handler: () => {
                            // console.log('Clicked NU');
                        }
                    }
                ]
            });
            alert.present();
        }


    }
});

In the example above, app and keyboard variables are imported from Ionic App and Keyboard classes, and nav is retrieved using ViewChild.
Here is another exemple a bit more complex that I found on ionic forums: https://gitlab.flashsoft.ro/snippets/4

Share the joy

Leave a Reply