Back button handler in jQuery Mobile (Android) PhoneGap

泪湿孤枕 提交于 2019-12-24 01:21:43

问题


Is there any way to handle back button (device backbutton) as default functionality to move back page? I need to implement the same functionality on back button goes to previous page. If there is no previous page (first page) it exit the application. Is this possible in PhoneGap?
I also need to pop page before going to push another page is this posible in jQuery?


回答1:


Checking window.location.length would be the easiest way to determine if you're on the first page, but this isn't available in Phonegap.

But since you're using JQM, you can either use the navigate event as Omar suggests or could manually count the number of pages shown and the number of pages gone back (same thing) and use this to determine if the first page is being shown and whether to exit the app. Something like this would work:

var pageHistoryCount = 0;
var goingBack = false;

$(document).bind("pageshow", function(e, data) {
    if (goingBack) {
        goingBack = false;
    } else {
        pageHistoryCount++;
        console.log("Showing page #"+pageHistoryCount);
    }
});

function exitApp() {
    console.log("Exiting app");
    navigator.app.exitApp();
}

function onPressBack(e) {
    e.preventDefault();
    if(pageHistoryCount > 0) pageHistoryCount--;
    if (pageHistoryCount == 0) {

        navigator.notification.confirm("Are you sure you want to quit?", function(result){
            if(result == 2){
                exitApp();
            }else{
                pageHistoryCount++;
            }
        }, 'Quit My App', 'Cancel,Ok');
    } else {
        goingBack = true;
        console.log("Going back to page #"+pageHistoryCount);
        window.history.back();
    }
}

function deviceready() {
    $(document).bind('backbutton', onPressBack);
}
$(document).bind('deviceready', deviceready);

As for the second part of your question:

Secondly i need to pop page before going to push another page is this posible in jquery ?

It's not clear what you're asking here. Do you mean you want to show some kind of popup content like a dialog between every page change? Please clarify then I can help you :-)



来源:https://stackoverflow.com/questions/17258550/back-button-handler-in-jquery-mobile-android-phonegap

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!