PhoneGap - android exit on backbutton
You need to wait for the device to be ready to add the event listener:
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady(){
document.addEventListener("backbutton", function(e){
if($.mobile.activePage.is('#homepage')){
e.preventDefault();
navigator.app.exitApp();
}
else {
navigator.app.backHistory();
}
}, false);
}
If you don't want to use Jquery Mobile, change $.mobile.activePage.is('#homepage') to document.getElementById('#homepage') on @mornaner answer, as on following code:
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady(){
document.addEventListener("backbutton", function(e){
if(document.getElementById('#homepage')){
e.preventDefault();
navigator.app.exitApp();
}
else {
navigator.app.backHistory()
}
}, false);
}
Through this way, don't need to download Jquery Mobile gibberish only for this purpose. Also, activePage is deprecated as of JQuery mobile 1.4.0 and will be removed from 1.5.0. (Use the getActivePage() method from the pagecontainer widget instead)
If you don't want to use any library, you can use window.location.hash to get the "panel" your app is on. Example :
function onDeviceReady(){
document.addEventListener("backbutton", function(e){
if(window.location.hash=='#home'){
e.preventDefault();
navigator.app.exitApp();
} else {
navigator.app.backHistory()
}
}, false);
}
document.addEventListener("deviceready", onDeviceReady, false);