Reputation: 2325
In my PhoneGap android app, in my Index.html page in OnDeviceReady() method I have added the following function for backbutton event listener.
document.addEventListener("backbutton", function(e) {
var sPath=window.location.pathname;
var sPage = sPath.substring(sPath.lastIndexOf('/') + 1);
if(sPage == "index.html"){
e.preventDefault();
// My action
return false;
} else {
return true;
}
}, false);
Problem Facing:
In my HomePage(Index.html) its working fine. If i press back button it gets closed.
But in all other pages (Page1.html,Page2.html,Page3.html,Page4.html) i havn't created backbutton event listener but nothing happens when i press back key.
Upvotes: 0
Views: 2904
Reputation: 434
You can try by adding the following javascript code:
document.addEventListener("backbutton", function(e) {
var sPath=window.location.pathname;
var sPage = sPath.substring(sPath.lastIndexOf('/') + 1);
if(sPage == "index.html"){
e.preventDefault();
// Method to close Phonegap application
navigator.app.exitApp();
} else {
// Method to go back to previous page
navigator.app.backHistory();
}
}, false);
Alternate approach which definitely works but uses two JavaScript files...
I have used the following code for pages other than index.html :
// Wait for Cordova to load
document.addEventListener("deviceready", onDeviceReady, false);
// Cordova is ready
function onDeviceReady() {
document.addEventListener("backbutton", function(e){
e.preventDefault();
navigator.app.backHistory();
return false;
}, true);
}
And on Home page you can add navigator.app.exitApp(); and remove navigator.app.backHistory();
Already answered here: PhoneGap - android exit on backbutton
Upvotes: 1