How to control back button in mobile ?!

how to control back button in mobile ?!
( when click back button do exit page ?!! )

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

function onBackKeyDown() {
        alert("back button pressed");
}

this function on device ready ?

1 Like

There is no need. Just place it at the bottom of app.js. Im not sure what you mean by exit page

for exit app do

function onBackKeyDown() {
        navigator.app.exitApp();
}

but to return home you can

   function onBackKeyDown() {
      mainView.router.navigate('/', {});
}

i can use this function in phonegab ?!!

$(window).on(“navigate”, function (event, data) {
var direction = data.state.direction;
if (direction == ‘back’) {
// do something
}
});

1 Like

Can you elaborate on your use case? I do not think you can access that in phonegap. Ideally, in your app you would remove your back button listener and enable pushState: true and the back button will work for navigating history.

var app = new Framework7({
     ...
     pushState: true,
     ...
});

then in app you can do mainView.router.history to view your history

if thats not working because you have to override the back button action to force the app to go back one state in the history:
function onBackKeyDown() {
mainView.router.back()
}

I use this method because I want the back button close popups, panels, etc (if exists) and close the app if we are at home page.

app = new Framework7({
    // App root element
    root: '#app',
    // App Name
    name: 'XXXXXXXX',
    init:false,
    panel: { 
      swipe: 'right',
    },
    smartSelect: {
        closeOnSelect: true,
    },
    // App id
    id: 'com.XXXXXXXX.app',

    popup: {
        closeByBackdropClick: false,
    },

    methods: {
        onBackKeyDown: function() {

            var leftp = app.panel.left && app.panel.left.opened;
            var rightp = app.panel.right && app.panel.right.opened;

            if ( leftp || rightp ) {

                app.panel.close();
                return false;
            }else if ($$('.modal-in').length > 0) {
              
                app.dialog.close();
                app.popup.close();
                return false;
            } else if (app.views.main.router.url == '/home/') {

                    navigator.app.exitApp();
            } else {

                mainView.router.back();
           }

}

...
2 Likes

very thanks :sweat_smile: