1
votes

I am using Cordova version 3.6 to create my first mobile application. I want to use the back button of the device to exit the application when reached the home page. I went through the following resources however am not able to achieve the purpose.

http://cordova.apache.org/docs/en/3.6.0/cordova_events_events.md.html#backbutton

PhoneGap - android exit on backbutton

backbutton confirm exit app android + phonegap + jquery

My Code:

Js:

function onLoad() {
        document.addEventListener("deviceready", onDeviceReady, false);
    }

function onDeviceReady() {
// Register the event listener
document.addEventListener("backbutton", onBackKeyDown, false);
}

function onBackKeyDown() {
document.addEventListener("backbutton", function(e){
if($('body').is('#main')){ //main is the home page id.. 
    e.preventDefault();
    navigator.app.exitApp();    
} else {
    navigator.app.backHistory()
}
}, false);
}

HTML:

Thanks for your time and efforts.

2

2 Answers

2
votes

Adding a listener to the backbutton again in the event handler doesn't make much sense. So remove document.addEventListener from onBackKeyDown(). And pass the event to the function.

function onBackKeyDown(e) {
  if($('body').is('#main')){ //main is the home page id.. 
    e.preventDefault();
    navigator.app.exitApp();    
  } else {
    navigator.app.backHistory()
  }
}
0
votes

You must add
<script type="text/javascript" src="yourpath/cordova.js"> </script>

to you html file. Type true place for your path