Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PhoneGap - android exit on backbutton

I am trying to program RSS reader using jquery mobile and cordova. My RSS reader consists of 3 pages (in same HTML document: page1, page2, page3). I am trying to override (hardware)backbutton behaviour so it would exit the program. To check that I am not doing any mistakes in project setup I have used PhoneGap example project and loaded it in Eclipse. Every sample function worked so I have moved my index.html and res folder to phonegap example. In my index.html I import the folowing scripts:

<script src="res/jquery-1.7.1.min.js"></script> <script src="res/jquery.mobile-1.1.1.min.js"></script> <script type="text/javascript" charset="utf-8" src="cordova-2.0.0.js"></script> <script type="text/javascript" charset="utf-8" src="main.js"></script> 

and my main.js file look like this:

document.addEventListener("backbutton", function(e){ if($.mobile.activePage.is('#homepage')){     e.preventDefault();     navigator.app.exitApp(); } else {     navigator.app.backHistory() } }, false); 

You can check version of my scripts in first code sample. Any ideas on how I could get the code working so it would simply exit app when I press backbutton on my Xperia Arc? I can upload my full code if needed.

EDIT: I have tested phonegap(cordova) beep function on my android phone and it works so this doesnt have anything with bad script implementation. It must be something in main.js file. Maybe some compatibility issue with jquerymobile backbutton functions and phonegap backbutton function.

like image 355
horin Avatar asked Sep 09 '12 10:09

horin


1 Answers

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); } 
like image 118
mornaner Avatar answered Oct 04 '22 12:10

mornaner