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 = || || ||;

    if (activePortal) {
    } else if ( {;

    } else if (this.keyboard.isOpen()) {
    else {
        if (this.nav.canGoBack()) {
        } else {

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


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:

Share the joy

Leave a Reply