(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

Leave a Reply

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