Softy Devel
Softy Devel

Reputation: 81

Disable / Override the Android Back button in Cordova 3.5

Per the Cordova documentation for version 3.5:

http://cordova.apache.org/docs/en/3.5.0/cordova_events_events.md.html#Events

I used the following code in an attempt to disable the back button. The onDeviceReady event fires but the back button event does not.

// Wait for device API libraries to load
//
function onLoad() {
    document.addEventListener("deviceready", onDeviceReady, false);
}

// device APIs are available
//
function onDeviceReady() {
    // Register the event listener
    document.addEventListener("backbutton", onBackKeyDown, false);
}

// Handle the back button
//
function onBackKeyDown() {
}

Amongst other interesting messages I am getting this message in my console:

exec() call to unknown plugin App.

I've seen several answers to this issue including the following to edit the config.xml file and add this:

<feature name="App">
     <param name="android-package" value="org.apache.cordova.App" />
</feature>

None of this is working.

Upvotes: 1

Views: 4955

Answers (2)

Lee Crossley
Lee Crossley

Reputation: 1280

To disable the native back button functionality you need to call preventDefault() on the event object passed to the handler:

document.addEventListener("backbutton", onBackKeyDown, false);

function onBackKeyDown(e) {
    e.preventDefault();
}

If you are getting other errors, I'd suggest removing and re-adding the android platform (make sure you have the latest version of Cordova installed first):

$ npm update cordova -g
$ cordova platform remove android
$ cordova platform add android

It would be best if you could share more of your project, so I can see where something is going wrong. Other checks you can do:

  • Ensure you have all plugins installed for any other functionality you might be using cordova plugin ls will give you a list of any installed.

  • Ensure you reference <script type="text/javascript" src="cordova.js"></script>.

  • Check the device ready event is being fired.

  • Check there are no JavaScript errors when you debug in Safari dev tools with the app running.

Upvotes: 3

Softy Devel
Softy Devel

Reputation: 81

Tipped off by this error: exec call to unknown plugin App

I examined the App.java file which holds the App plugin included with the cordova build, I found the following line:

protected static final String TAG = "CordovaApp";

This did not match the corresponding exec() call made in the cordova.js file which came with 3.5. So, I changed it to

protected static final String TAG = "App";

Now the Event overrides for cordova all work per the documentation.

Cheers.

Upvotes: 1

Related Questions