Catching Android’s Back Button in PhoneGap

This little bit of code is going to be useful to those of you developing a “singe page” app inside of PhoneGap. This applies to Sencha Touch (big fan), but doesn’t as much to jQuery mobile and jQTouch, as it’s a multi-page/navigation based event framework (it uses the app’s url string to do things like move around to different link anchors). This is really important on these single page apps because the Android hardware back button will send the PhoneGap app to the background. You need some way to intercept it so you can start building your own history management mechanism. Sounds fun, right? It’s actually not that hard.

On app initialization, add an event listener for Android’s back button, and the callback to handle it. PhoneGap takes care of the interface between Android and your app.

document.addEventListener("backbutton", backKeyDown, true); 
function backKeyDown() { 
     // Call my back key code here.
 	alert('go back!');
}

That’s enough to get you started, and it should be pretty apparent if it works or not.

How about history management? It will depend on the app and what makes sense, BUT you’ll probably want to create a history array, and pop off some value that directs the app each time you hit the hardware back button. Here’s another idea: change the destination of the back button depending on the view. I personally like the idea of the latter because apps built on Sencha Touch are going to have easy tie-ins through predefined listeners JS Objects that define screen elements like buttons.

About these ads
Tagged , , , , ,

27 thoughts on “Catching Android’s Back Button in PhoneGap

  1. JR says:

    I did a copy-paste of those four lines of code and the back button still exits my app. :-(

  2. Oskar says:

    I can’t make it work either. I’m using the latest version of Phonegap (0.9.4). When running on the device I get a console.log message saying “JSCallback Error: Request failed. at file:///android_assets/www/lib/phonegap.0.9.4.js:711″

    Any ideas of how to make it work?

  3. Sandy Meier says:

    try

    document.addEventListener(“backKeyDown”, backKeyDown, true);

  4. Daniel says:

    Thanks, this is what i was looking for. I just copied and pasted, i put it inside the onReady function in sencha touch.

  5. Mahendra says:

    Do you have any idea how can we handle the back button click in a single page webapp using PhoneGap. I am just animating the div tags based on the menu / navigation options selected by the user.

    Thanks.

    • Sure. Add whatever code you need inside of backKeyDown() to accomplish the task. All this listener is doing is waiting for you to hit the key – it doesn’t necessarily have to go “back” to another page. The simplest implementation is leaving it empty so hitting the back button doesn’t exit the user out of your app.

  6. Mathias says:

    Hello there,
    is there any posibility to to this only with javascripts (no Phonegap)?

    Thanks
    Mathias

  7. Mathias says:

    Over #hashes you can go back with the back button on a single html-page:

    http://jquerymobile.com/demos/1.0b2/docs/pages/multipage-template.html

    That’s what I was searchin for ;)

    • anlazarov says:

      That really doesn’t happen in my case, using the #hashe :( Plus that it also hangs when I actually press a button pointing in the reverse direction :/

      Do you know what could that be?

  8. ggendre says:

    If you use senchatouch with phonegap, you can also use the routing system of senchatouch.
    I had a few hints about how it works here :

    http://www.sencha.com/forum/showthread.php?179816-help-with-history-back-and-router.draw&p=731461#post731461

  9. ajay says:

    I am using jqueryMobile(1.0.1) and phonegap(1.5.0). Everytime I launched the app, on clicking device “Back Button”, back button handler calls but when i moves to next div and then after I clicks on device back button nothing happens.

    My code is like this – I am calling onLoad function in body tag.

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

    function onDeviceReady()
    {
    document.addEventListener(“backbutton”, onBackKeyDown, false);
    }

    function onBackKeyDown()
    {
    alert(‘onBackKeyDown’);
    }

    What I am doing wrong? Please do reply.

  10. kapitan says:

    how to run apps in background using phonehap

  11. christopher says:

    This my code not working my android phone and tab plz help me

    function Load() {
    alert(’22’);
    document.addEventListener(“deviceready”, onDeviceReady, false);
    }

    function onDeviceReady() {

    document.addEventListener(“backbutton”, onBackKeyDown, false);

    }

    function onBackKeyDown() {
    alert(‘Back Button!’);
    navigator.app.exitApp();

    }

  12. christopher says:

    I fix back button issue in android mobile and tab plz use below code

    plz put this code to device defined page
    do’nt put the code to index.html

    function onload() { // onload function cal to home.html
    try {
    document.addEventListener(“deviceready”, onDR, false);
    }
    catch (ex) {
    }
    }
    function onDR(){
    document.addEventListener(“backbutton”, backKeyDown, true);

    }
    function backKeyDown() {
    alert(‘go back’);
    navigator.app.exitApp();

    }

    any query plz mail to christopher.jul@gmail.com

  13. Temp says:

    With a PhoneGap wrapper and Sencha Touch 2, to drive the NestedList back:

    In the GAP init JS

    document.addEventListener(“backbutton”, backKeyDown, true);
    function backKeyDown()
    {
    mySTapp.fireBack();
    }

    In the ST2 app:

    fireBack: function()
    {
    if (window.phoneGapActive === true)
    {
    var nestedList = Ext.getCmp(‘idList’);
    if (nestedList !== undefined)
    {
    nestedList.onBackTap();
    console.log(‘Back intercepted’);
    }
    }
    }

    It works fine in Android.

  14. Raviraj says:

    This is My Controller Code

    launch: function () {
    this.callParent(arguments);
    console.log(“launch……..”);

    if (Ext.os.is(‘Android’)) {
    window.addEventListener(“backbutton”, Ext.bind(onBackKeyDown, this), false);

    function onBackKeyDown(eve) {

    alert(‘back button pressed’);

    eve.preventDefault();

    //do something

    }
    }
    },

    init: function () {
    this.callParent(arguments);
    console.log(“init……”);
    }

    Problem — onBackKeyDown function is not call Please help me

    • loki says:

      jus try with this code in ur launch method

      this.backdown = Ext.bind(this.onBackBtnTap, this);
      document.addEventListener(“backbutton”, this.backdown);

      define this method outside the launch
      onBackBtnTap:function(){
      //backbutton tap captured here
      }

  15. Nayan Dabhi says:

    i have create an app using sencha touch v2 with phonegap.
    i have to prevent the hardware back button of android mobile.
    below code i have to used in my app.js of the android file.

    launch: function() {
    alert(“in onready”);
    document.addEventListener(“backbutton”, onBackKeyDown, false);

    function onBackKeyDown() {
    alert(“back key pressed”);
    }
    },

    is there any kind of mistake??
    i can only get alert msg “in onready” but could not going on to the function onBackKeyDown() function.
    any one can give the solution…!

  16. Rajagopalan S says:

    I have created an webpage using Jquery and css only. I have created an app for it by using Adobe phonegap cloud. I have included the phonegap.0.9.5.1.js to the html file. When i try to capture for the back button event, i am not able to do so? Can you suggest me some solutions?

    • lokeshis says:

      document.addEventListener(“backbutton”, backKeyDown, true);

      function backKeyDown() {
      // Call back key code here.
      …..
      }

      note: if possible try to add eventlistener in ondeviceReady function

  17. Thibka says:

    Thanks a lot, this works fine for me. For those who encounter problems, don’t forget to put the code inside the ondevice ready :

    document.addEventListener(“deviceready”,onDeviceReady,false);
    function onDeviceReady () {
    document.addEventListener(“backbutton”, backKeyDown, true);
    function backKeyDown() {
    alert(‘go back!’);
    }
    }

    And in order to have it working you also have to import cordova.js before :

  18. […] CATCHING ANDROID’S BACK BUTTON IN PHONEGAP […]

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

Join 399 other followers

%d bloggers like this: