onBackKeyDown can't go back to previous page

I got this code that works fine exept for the last else if.
If i’m in Home page, create a Toast and close app.
If and panel, or modal is open, back button closes.
But if i’m in other page than the home page Back Button not work, do nothing.

var mainView = app.views.create('.view-main');

document.addEventListener("backbutton", onBackKeyDown, false);

function onBackKeyDown(e) { 
    if (app.view.main.history.length == 1) {
        app.toast.create({
          text: 'Presione SALIR para cerrar la app.',
          closeButton: true,
          closeButtonText: 'Salir',
            closeButtonColor: 'lime',
          on: {
            close: function () {
              navigator.app.exitApp();
                e.preventDefault();
            },
          }
        }).open();
    } else {
        if ($$('.modal-in').length > 0) {
        app.popup.close();
        //return false;
        } else if ($$('.card-opened').length > 0) {
            app.card.close('.card-expandable');       
        } else if ($$('.panel-right').length > 0) {
            app.panel.close();
        } else if (app.view.main.history.length > 1){
            mainView.router.back();
        }
    }
    return true;
};

Hi there,

  • This might work for your scenario:

function BackKeyPressed(){
var expression = app.view.main.router.currentRoute.name;
switch(expression){
case ‘your_route_name_1’:
app.view.main.router.navigate(’/path_to_route/’);
break;
case ‘your_route_name_2’:
app.view.main.router.navigate(’/path_to_route/’);
break;
default:
app.view.main.router.back();
}
}

all the best!

Thanks for your reply.

I made my code work, the error was with panel close by back button.
Commented that and works fine.

The code check:

    1. if you are on home page, if true create a toast asking you want to close app. If false =>
    1. check for a modal open, if true: close, if false =>
    1. check for an expandable card open, if true: close, if false =>
    1. go back to previous page.

    function onBackKeyDown(e) {
    if (app.view.main.router.currentRoute.name == “inicio” || app.view.main.history.length == 1) {
    app.toast.create({
    text: ‘Presione SALIR para cerrar la app.’,
    closeButton: true,
    closeButtonText: ‘Salir’,
    closeButtonColor: ‘lime’,
    closeTimeout: 2000,
    on: {
    closeButtonClick: function () {
    navigator.app.exitApp();
    e.preventDefault();
    },
    }
    }).open();
    } else {
    if ($$(’.modal-in’).length > 0) {
    app.popup.close();
    return false;
    } else if ($$(’.card-opened’).length > 0) {
    app.card.close(’.card-expandable’);
    //} else if ($$(’.panel-right’).length > 0) {
    // app.panel.close();
    } else {
    mainView.router.back();
    }
    }
    return true;
    };