Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Close cordova app on back button

I have the following logic for my mobile app using cordova and angular.js

Process my logic in mobile.js included in index.html like saving the files on sdcard then redirect the user to the second html page using

window.location.href="main.html";

which will use the files put in sdcard by mobile.js

The issue I'm facing is that when I am on the homepage on main.html and the user presses the back button it comes back to the index.html file and then, after processing goes back to main.html instead of App closing.

I tried using the history.length object with the "backbutton" eventListener

        document.addEventListener('deviceready',function(){
        document.addEventListener('backbutton',function(e){
            console.log("history is "+history.length);
            if(history.length==1){
                e.preventDefault();
                navigator.app.exitApp();
            }
            else{
                navigator.app.backHistory();
            }
        },false);
    },false);

but it doesn't decrease the length when going back, only increases it, so the app goes back to index.html.(history.length is always greater than 1)

I have looked the solution available, like

document.addEventListener("backbutton", function(e){
if($.mobile.activePage.is('#homepage')){
    /* 
     Event preventDefault/stopPropagation not required as adding backbutton
      listener itself override the default behaviour. Refer below PhoneGap link.
    */
    //e.preventDefault();
    navigator.app.exitApp();
}
else {
    navigator.app.backHistory()
} 
}, false);

but the issue in using it is, if the user goes to

second-page->homepage->third-page->homepage

the app will exit, but instead should go to the third-page.

like image 772
Satpal Tanan Avatar asked Feb 27 '15 13:02

Satpal Tanan


1 Answers

You could use the jQuery mobile pageload event to keep your own history list, whose length does decrease when you go back. Something like this (untested off the top of my head, so might not be exactly correct):

var pageHistory = [];

$(document).on("deviceready", onDeviceReady);


function onDeviceReady(){
    $(document).on("pagecontainerload", onPageLoad);
    $(document).on("backbutton", onBackButton);
}

function onBackButton(e){
    e.preventDefault();
    pageHistory.pop();
    if(pageHistory.length==0){
        navigator.app.exitApp();
    }
    else{
        navigator.app.backHistory();
    }
}

function onPageLoad(e, ui){
    var pageId = ui.toPage.attr('id');
    if(pageId !== pageHistory[pageHistory.length]){
        pageHistory.push(pageId);
    }    
}
like image 61
DaveAlden Avatar answered Oct 04 '22 10:10

DaveAlden