Using Dropbox datastores in a Cordova app

// By Steve Marx • Jun 02, 2014

Update: The Sync and Datastore SDK has been deprecated. Learn more here.

Apache Cordova is a platform for building cross-platform mobile apps using HTML, CSS, and JavaScript. Developers sometimes ask whether they can use Dropbox datastores in a Cordova app, and the answer is yes! The JavaScript Datastores SDK works as-is in a Cordova app. All you need to do is tell the library to use the Cordova "auth driver," which takes just a single line of code.

Migrating the tasks example to Cordova

To learn about how to build Cordova apps using the Datastore API, I converted the tasks example that ships with the JavaScript SDK to run in a Cordova app. I published the final code on Github in the cordova-datastores-example repository.

The modifications I made were quite minimal. I made a few cosmetic changes (added a <meta name="viewport"> tag and updated some CSS), but otherwise I didn't do any work to optimize the UI for the phone form factor. In terms of making the code run properly in a Cordova app, I really only had to change the auth driver with the following line of code:

client.authDriver(new Dropbox.AuthDriver.Cordova());

The sample app originally used the default redirect auth driver. With that driver, the page is loaded again after authorization, so that code only checked for authorization on page load. To work better with the Cordova auth driver (and others like the pop-up auth driver), I refactored the code slightly. The new auth code looks like this: 

function auth_callback() {
    if (client.isAuthenticated()) { ... }
    else { ... }
$('#loginButton').click(function (e) {
    // Start the OAuth authorization process.
// Try to finish OAuth authorization.
client.authenticate({ interactive: false }, auth_callback);

This code may be better than the original tasks example code because it will work with any auth driver.

Get the code

The full source code for the Cordova sample is on Github: To get the code running, you'll need to create a new Cordova project and then clone that repository into the wwwdirectory. Full instructions are in the README

file on Github. Feel free to open issues or submit pull requests on Github!

// Copy link