(Android) PhoneGap Cordova 1.5 menubutton and searchbutton with jQuery Mobile

Using PhoneGap (Cordova) 1.5, I ran into an issue with the physical buttons on the Android device, specifically I was trying to bind handlers to “menubutton”, “searchbutton”, and use them to navigate within a jQuery Mobile app. However, these buttons only worked on the first/initial jQuery Mobile page. After this page was navigated from, the buttons no longer worked.

After attempting many different solutions and workarounds, I came across a very simple solution.

A few lines from the bottom of the cordova.js (1.5.0) file, you will find the line:

// boot up once native side is ready
channel.onNativeReady.subscribe(_self.boot);

Change it to:

// boot up once native side is ready
channel.onNativeReady.subscribeOnce(_self.boot);

I believe this has something to do with a conflict in the way jQuery Mobile binds to the document.

For good measure, here is the JavaScript I used in the <head> of my index.html

$(document).bind("mobileinit", function(){
    //first init
});

$(document).on("pageinit", function(){
    //each jqm page init
});

//From PhoneGap's documentation on creating listeners for buttons
function init(){
    document.addEventListener("deviceready", onDeviceReady, false);
}

//when phonegap is ready
function onDeviceReady() {
    //event listeners for buttons
    document.addEventListener("menubutton", menuButton, false);
    document.addEventListener("searchbutton", searchButton, false);
}

//when menu button is pressed
function menuButton() {
    //change to main menu page
    $.mobile.changePage("#menu", {transition: "slidedown"});
}

//when search button is pressed
function searchButton() {
    //change to search page
    $.mobile.changePage("#search", {transition: "slideup"});
}
This entry was posted in Mobile Development and tagged , , , , , , , . Bookmark the permalink.

3 Responses to (Android) PhoneGap Cordova 1.5 menubutton and searchbutton with jQuery Mobile

  1. Jan says:

    Thanks Man for that hint!
    Works fine for me..

  2. Mike Panter says:

    Thanks. Using the deviceReady event (as shown) instead of body onload, solved the event firing for me. I am using Cordova 1.7.0.js – which uses the “subscribeOnce” method.

    • Ahmad says:

      Nice writeup. My einerxepce was very similar. Now that I have PG setup, it is very easy to use. PhoneGap might make some more progress if they could somehow make an setup process that doesn’t take a new developer 20 hours to setup and configure to test it out the first time.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>