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.

Join the Conversation

27 Comments

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

  2. 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. Thanks, this is what i was looking for. I just copied and pasted, i put it inside the onReady function in sencha touch.

  4. 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.

    1. 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.

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

    Thanks
    Mathias

    1. 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?

  6. 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.

  7. 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();

    }

  8. 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

  9. 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.

  10. 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

    1. 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
      }

  11. 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…!

  12. 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?

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

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

      note: if possible try to add eventlistener in ondeviceReady function

  13. 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 :

Leave a comment

Hey there! Come check out all-new content at my new mistercameron.com!