Developing Your First Cordova Application

Hazem Saleh

February 2016

In this article, you will develop, build, and deploy your first Apache Cordova application from scratch. The application you will develop is a Sound Recorder utility that you can use to record your voice or any sound and play it back. In this chapter, you will learn about the following topics:

  • Generating your initial Apache Cordova project artifacts by utilizing the Apache Cordova Command-line Interface (CLI)
  • Developing and building your mobile application from the initial Cordova generated code
  • Deploying your developed mobile application to a real Android mobile device to see your application in action

(For more resources related to this topic, see here.)

An introduction to Cordova CLI

In order to create, develop, build, and test a Cordova application, you first need to use the Cordova CLI. Using this, you can create new Apache Cordova project(s), build them on mobile platforms such as iOS, Android, Windows Phone, and so on, and run them on real devices or within emulators. Note that in this chapter, we will focus on deploying our Sound Recorder application in Android devices only.

In the next chapter, we will learn how to deploy our Sound Recorder application in iOS and Windows Phone devices.

Installing Apache Cordova

Before installing Apache Cordova CLI, you need to make sure that you install the following software:

After installing Node.js, you should be able to run Node.js or node package manager (npm) from the command line. In order to install Apache Cordova using npm, run the following command (you can omit sudo if you are working in a Windows environment):

> sudo npm install -g cordova

It's worth mentioning that npm is the official package manager for Node.js and it is written completely in JavaScript. npm is a tool that allows users to install Node.js modules, which are available in the npm registry.

The sudo command allows a privileged Unix user to execute a command as the super user, or as any other user, according to the sudoers file. The sudo command, by default, requires you to authenticate with a password. Once you are authenticated, you can use the command without a password, by default, for 5 minutes.

After successfully installing Apache Cordova (Version 3.4.0), you should be able to execute Apache Cordova commands from the command line, for example, the following command will show you the current installed version of Apache Cordova:

> cordova -version

In order to execute the Cordova commands without any problem, you also need to have Apache Ant installed and configured in your operating system.

You can download Apache Ant from The complete instructions on how to install Ant are mentioned at

Generating our Sound Recorder's initial code

After installing Apache Cordova, we can start creating our Sound Recorder project by executing the following command:

> cordova create soundRecorder com.jsmobile.soundrecorder SoundRecorder

After successfully executing this command, you will find a message similar to the following one (note that the location path will be different on your machine):

Creating a new cordova project with name "SoundRecorder" and id "com.jsmobile.soundrecorder" at location "/Users/xyz/projects/soundRecorder"

If we analyze the cordova create command, we will find that its first parameter represents the path of your project. In this command, a soundRecorder directory will be generated for your project under the directory from which the cordova create command is executed. The second and third parameters are optional. The second parameter, com.jsmobile.soundrecorder, provides your project's namespace (it should be noted that in Android projects, this namespace will be translated to a Java package with this name), and the last parameter, SoundRecorder, provides the application's display text. You can edit both these values in the config.xml configuration file later, which will be illustrated soon.

The following screenshot shows our SoundRecorder project's generated artifacts:


The Sound Recorder's initial structure

As shown in the preceding screenshot, the generated Apache Cordova project contains the following main directories:

  • www: This directory includes your application's HTML, JavaScript, and
    CSS code. You will also find the application's starting page (index.html), along with various subdirectories, which are as follows:
    • css: This directory includes the default Apache Cordova application's CSS file (index.css)
    • js: This directory includes the default Apache Cordova application's JavaScript file (index.js)
    • img: This directory includes the default Apache Cordova application's logo file (logo.png)
  • config.xml: This file contains the application configuration. The following code snippet shows the initial code of the config.xml file:
    <?xml version='1.0' encoding='utf-8'?>
    <widget id="com.jsmobile.soundrecorder" version="0.0.1"
           A sample Apache Cordova application that responds to the deviceready event.
       <author email="" href="">
           Apache Cordova Team
       <content src="index.html" />
       <access origin="*" />
  • As shown in the preceding config.xml file, config.xml contains the following elements that are available on all the supported Apache
    Cordova platforms:
  • The <widget> element's id attribute represents the application's namespace identifier as specified in our cordova create command, and the <widget> element's version attribute represents its full version number in the form of major.minor.patch.
  • The <name> element specifies the application's name.
  • The <description> and <author> elements specify the application's description and author, respectively.
  • The <content> element (which is optional) specifies the application's starting page that is placed directly under the www directory. The default value is index.html.
  • The <access> element(s) defines the set of external domains that the application is allowed to access. The default value is *, which means that the application is allowed to access any external server(s).

    Specifying the <access> element's origin to * is fine during application development, but it is considered a bad practice in production due to security concerns. Note that before moving your application to production, you should review its whitelist and declare its access to specific network domains and subdomains.

  • There is another element that is not included in the default config.xml, and this is the <preference> element. The <preference> element(s) can be used to set the different preferences of the Cordova application and can work on all or a subset of the Apache Cordova-supported platforms. Take the example of the following code:
    <preference name="Fullscreen" value="true" />
  • If the Fullscreen preference is set to true, it means that the application will be in fullscreen mode on all Cordova-supported platforms (by default, this option is set to false). It is important to note that not all preferences work on all Cordova-supported platforms. Consider the following example:
    <preference name="HideKeyboardFormAccessoryBar" value="true"/>
  • If the HideKeyboardFormAccessoryBar preference is set to true, then the additional helper toolbar, which appears above the device keyboard, will be hidden. This preference works only on iOS and BlackBerry platforms.
  • platforms: This directory includes the application's supported platforms. After adding a new platform using Apache Cordova CLI, you will find a newly created directory that contains the platform-specific generated code under the platforms directory. The platforms directory is initially empty because we have not added any platforms yet. We will add support to the Android platform in the next step.
  • plugins: This directory includes your application's used plugins. If you aren't already aware, a plugin is the mechanism to access the device's native functions in Apache Cordova. After adding a plugin (such as the Media plugin) to the project, you will find a newly created directory under the plugins directory, which contains the plugin code. Note that we will add three plugins in our Sound Recorder application example.
  • merges: This directory can be used to override the common resources under the www directory. The files placed under the merges/[platform] directory will override the matching files (or add new files) under the www directory for the specified platform (the [platform] value can be iOS, Android, or any other valid supported platform).
  • hooks: This directory contains scripts that can be used to customize Apache Cordova commands. A hook is a piece of code that executes before and/or after the Apache Cordova command runs.

An insight into the www files

If we look in the www directory, we will find that it contains the following three files:

  • index.html: This file is placed under the application's www directory, and it contains the HTML content of the application page
  • index.js: This file is placed under the www/js directory, and it contains a simple JavaScript logic that we will illustrate soon
  • index.css: This file is placed under the www/css directory, and it contains the style classes of the HTML elements

The following code snippet includes the most important part of the index.html page:

<div class="app">
   <h1>Apache Cordova</h1>
   <div id="deviceready" class="blink">
       <p class="event listening">Connecting to Device</p>
       <p class="event received">Device is Ready</p>
<script type="text/javascript" src="cordova.js"></script>
<script type="text/javascript" src="js/index.js"></script>
<script type="text/javascript">

The index.html page has a single div "app", which contains a child div "deviceready". The "deviceready" div has two paragraph elements, the "event listening" and "event received" paragraphs. The "event received" paragraph is initially hidden as indicated by index.css:

.event.received {

In the index.html page, there are two main JavaScript-included files, as follows:

  • cordova.js: This file contains Apache Cordova JavaScript APIs
  • index.js: This file contains the application's simple logic

Finally, the index.html page calls the initialize() method of the app object. Let's see the details of the app object in index.js:

var app = {
   initialize: function() {
   bindEvents: function() {
       document.addEventListener('deviceready', this.onDeviceReady, false);
   onDeviceReady: function() {
   receivedEvent: function(id) {
       var parentElement = document.getElementById(id);
       var listeningElement = parentElement.querySelector('.listening');
       var receivedElement =

       listeningElement.setAttribute('style', 'display:none;');
       receivedElement.setAttribute('style', 'display:block;');

       console.log('Received Event: ' + id);

The initialize() method calls the bindEvents() method, which adds an event listener for the 'deviceready' event. When the device is ready, the onDeviceReady() method is called, and this in turn calls the receivedEvent() method of the app object.

In the receivedEvent() method, the "event listening" paragraph is hidden and the "event received" paragraph is shown to the user. This is to display the Device is Ready message to the user once Apache Cordova is fully loaded.

It is important to note that you must not call any Apache Cordova API before the 'deviceready' event fires. This is because the 'deviceready' event fires only once Apache Cordova is fully loaded.

Now you have an Apache Cordova project that has common cross-platform code,
so we need to generate a platform-specific code in order to deploy our code on a
real device. To generate Android platform code, you need to add the Android platform as follows:

> cd soundRecorder
> cordova platform add android

In order to add any platform, you need to execute the cordova platform command from the application directory. Note that in order to execute the cordova platform command without problems, you need to perform the following instructions:

  • Have Apache Ant installed and configured in your operating system as described in the Installing Apache Cordova section
  • Make sure that the path to your Android SDK platform tools and the tools directory are added to your operating system's PATH environment variable

After executing the cordova platform add command, you will find a new subdirectory Android added under the soundRecorder/platforms directory, which is added by Android. In order to build the project, use the following command:

> cordova build

Finally, you can run and test the generated Android project in the emulator by executing the following command:

> cordova emulate android

You might see the ERROR: No emulator images (avds) found message flash if no Android AVDs are available in your operating system. So, make sure you create one!

The following screenshot shows our Sound Recorder application's initial screen:


It is recommended that you make your code changes in the root www directory,
and not in the platforms/android/assets/www directory (especially if you are targeting multiple platforms) as the platforms directory will be overridden every time you execute the cordova build command, unless you are willing to use Apache Cordova CLI to initialize the project for a single platform only.

Developing Sound Recorder application

After generating the initial application code, it's time to understand what to do next.

Sound Recorder functionality

The following screenshot shows our Sound Recorder page:


When the user clicks on the Record Sound button, they will be able to record their voices; they can stop recording their voices by clicking on the Stop Recording button. You can see this in the following screenshot:


As shown in the following screenshot, when the user clicks on the Playback button, the recorded voice will be played back:


Sound Recorder preparation

In order to implement this functionality using Apache Cordova, we need to add the following plugins using the indicated commands, which should be executed from the application directory:

  • media: This plugin is used to record and play back sound files:
       > cordova plugin add
  • device: This plugin is required to access the device information:
       > cordova plugin add
  • file: This plugin is used to access the device's filesystem:
       > cordova plugin add

In order to apply these plugins to our Apache Cordova project, we need to run the cordova build command again from the project directory, as follows:

> cordova build

Sound Recorder details

Now we are done with the preparation of our Sound Recorder application.
Before moving to the code details, let's see the hierarchy of our Sound Recorder application, as shown in the following screenshot:

The application's www directory contains the following directories:

  • css: This directory contains the custom application CSS file(s)
  • img: This directory contains the custom application image file(s)
  • js: This directory contains the custom application JavaScript code
  • jqueryMobile: This directory (which is a newly added one) contains jQuery mobile framework files

Finally, the index.html file contains the application's single page whose functionality was illustrated earlier in this section.

It is important to note that Apache Cordova does not require you to use a JavaScript mobile User Interface (UI) framework. However, it is recommended that you use a JavaScript mobile UI framework in addition to Apache Cordova. This is in order to facilitate building the application UI and speed up the application development process.

Let's see the details of the index.html page of our Sound Recorder application.
The following code snippet shows the included files in the page:

<link rel="stylesheet" type="text/css" href="css/app.css" />
<link rel="stylesheet" href="jqueryMobile/">
<script src="jqueryMobile/jquery-1.10.2.min.js"></script>
<script src="jqueryMobile/"></script>
<script type="text/javascript" src="cordova.js"></script>
<script type="text/javascript" src="js/app.js"></script>

In the preceding code, the following files are included:

  • app.css: This is the custom style file of our Sound Recorder application
  • The files required by the jQuery mobile framework, which are:
    • jquery-1.10.2.min.js
  • cordova.js: This is the Apache Cordova JavaScript API's file
  • app.js: This is the custom JavaScript file of our Sound Recorder application

It is important to know that you can download the jQuery mobile framework files from

The following code snippet shows the HTML content of our application's single page, whose id is "main":

<div data-role="page" id="main">
   <div data-role="header">
       <h1>Sound Recorder</h1>
   <div data-role="content">
   <div data-role="fieldcontain">
       <h1>Welcome to the Sound Recorder Application</h1>
       <p>Click 'Record Sound' button in order to start
recording. You will be able to see
          the playback button once the sound recording
       <input type="hidden" id="location"/>
       <div class="center-wrapper">
           <input type="button" id="recordSound" data-
icon="audio" value="Record Sound" class="center-button" data-
           <input type="button" id="playSound" data-
icon="refresh" value="Playback" class="center-button" data-

       <div data-role="popup" id="recordSoundDialog" data-
dismissible="false" style="width:250px">
           <div data-role="header">

           <div data-role="content">
               <div class="center-wrapper">
                   <div id="soundDuration"></div>
                   <input type="button" id="stopRecordingSound" value="Stop Recording"
                             class="center-button" data-

   <div data-role="footer" data-position="fixed">
       <h1>Powered by Apache Cordova</h1>

Looking at the preceding code, our Sound Recording page ("main") is defined by setting a div's data-role attribute to "page". It has a header defined by setting a div's data-role to "header". It has content defined by setting a div's data-role to "content", which contains the recording and playback buttons.

The content also contains a "recordSoundDialog" pop up, which is defined by setting a div's data-role to "popup". The "recordSoundDialog" pop up has a header and content. The pop-up content displays the recorded audio duration in the "soundDuration" div, and it has a "stopRecordingSound" button that stops recording the sound.

Finally, the page has a footer defined by setting a div's data-role to "footer", which contains a statement about the application.

Now, it's time to learn how we can define event handlers on the the page HTML elements and use the Apache Cordova API inside our defined event handlers to implement the application's functionality.

The following code snippet shows the page initialization code:

(function() {

   $(document).on("pageinit", "#main", function(e) {

         function onDeviceReady() {
               $("#recordSound").on("tap", function(e) {
                     // Action is defined here ...

function(event, ui) {
                     // Action is defined here ...

               $("#stopRecordingSound").on("tap", function(e) {
                     // Action is defined here ...

               $("#playSound").on("tap", function(e) {
                     // Action is defined here ...

         $(document).on('deviceready', onDeviceReady);


   // Code is omitted here for simplicity

   function initPage() {

In jQuery mobile, the "pageinit" event is called once during page initialization. In this event, the event handlers are defined and the page is initialized. Note that all of the event handlers are defined after the 'deviceready' event fires. The event handlers are defined for the following:

  • Tapping the "recordSound" button
  • Closing the "recordSoundDailog" dialog
  • Tapping the "stopRecordingSound" button
  • Tapping the "playSound" button

In initPage(), the "playSound" button is hidden as no voice has been recorded yet. As you noticed, in order to hide an element in jQuery mobile, you just need to call its hide() method. We can now see the details of each event handler; the next code snippet shows the "recordSound" tap event handler:

var recInterval;
$("#recordSound").on("tap", function(e) {

   var recordingCallback = {};

   recordingCallback.recordSuccess = handleRecordSuccess;
   recordingCallback.recordError = handleRecordError;


   var recTime = 0;

   $("#soundDuration").html("Duration: " + recTime + " seconds");


   recInterval = setInterval(function() {
                                 recTime = recTime + 1;
                                 $("#soundDuration").html("Duration: " + recTime + " seconds");
                             }, 1000);

The following actions are performed in the "recordSound" tap event handler:

  1. A call to the startRecordingSound(recordingCallback) function is performed. The startRecordingSound(recordingCallback) function is a helper function that starts the sound recording process using the Apache Cordova Media API. Its recordingCallback parameter represents a JSON object, which has the recordSuccess and recordError callback attributes. The recordSuccess callback will be called if the recording operation is a success, and the recordError callback will be called if the recording operation is a failure.
  2. Then, the "recordSoundDialog" dialog is opened and its "soundDuration" div is updated every second with the duration of the recorded sound.

The following code snippet shows the startRecordingSound(recordingCallback), stopRecordingSound(), and requestApplicationDirectory(callback) functions:

var BASE_DIRECTORY = "CS_Recorder";
var recordingMedia; 

function startRecordingSound(recordingCallback) {
   var recordVoice = function(dirPath) {
       var basePath = "";

       if (dirPath) {
           basePath = dirPath + "/";

       var mediaFilePath = basePath + (new Date()).getTime() +

       var recordingSuccess = function() {

       recordingMedia = new Media(mediaFilePath,
recordingSuccess, recordingCallback.recordError);

       // Record audio

   if (device.platform === "Android") {
       var callback = {};

       callback.requestSuccess = recordVoice;
       callback.requestError = recordingCallback.recordError;

   } else {


function stopRecordingSound() {

function requestApplicationDirectory(callback) {
   var directoryReady = function (dirEntry) {
   var fileSystemReady = function(fileSystem) {
       fileSystem.root.getDirectory(BASE_DIRECTORY, {create:
true}, directoryReady);                  
   window.requestFileSystem(LocalFileSystem.PERSISTENT, 0,
fileSystemReady, callback.requestError);

The next section illustrates the preceding code snippet.

Recording and playing the audio files back

In order to record the audio files using Apache Cordova, we need to create a Media object, as follows:

recordingMedia = new Media(src, mediaSuccess, mediaError);

The Media object constructor has the following parameters:

  • src: This refers to the URI of the media file
  • mediaSuccess: This refers to the callback that will be invoked if the media operation (play/record or stop function) succeeds
  • mediaError: This refers to the callback that will be invoked if the media operation (again a play/record or stop function) fails

In order to start recording an audio file, a call to the startRecord() method of the Media object must be performed. When the recording is over, a call to stopRecord() of the Media object method must be performed.

In startRecordingSound(recordingCallback), the function gets the current device platform by using device.platform, as follows:

  • If the current platform is Android, then a call to requestApplicationDirectory(callback) is performed in order to create an application directory (if it is not already created) called "CS_Recorder" under the device's SD card root directory using the Apache Cordova File API. If the directory creation operation succeeds, recordVoice() will be called by passing the application directory path as a parameter. The recordVoice() function starts recording the sound and saves the resulting audio file under the application directory. Note that if there is no SD card in your Android device, then the application directory will be created under the app's private data directory (/data/data/[app_directory]), and the audio file will be saved under it.
  • In the else block which refers to the other supported platforms (Windows Phone 8 and iOS), recordVoice() is called without creating an application-specific directory. At the time of writing this article, in iOS and Windows Phone 8, every application has a private directory, and applications cannot store their files in any place other than this directory, using the Apache Cordova APIs. In the case of iOS, the audio files will be stored under the tmp directory of the application's sandbox directory (the application's private directory). In the case of Windows Phone 8, the audio files will be stored under the application's local directory.

    Note that using the native Windows Phone 8 API (Window.Storage), you can read and write files in an SD card with some restrictions. However, until the moment you cannot do this using Apache Cordova; hopefully this capability will soon be supported by Cordova (

  • In recordVoice(), it starts creating a media file using the Media object's startRecord() function. After calling the media file's stopRecord() function and after the success of the recording operation, recordingCallback.recordSuccess will be called by recordingSuccess. The recordingCallback.recordSuccess function calls handleRecordSuccess, passing the audio file's full path mediaFilePath as a parameter.
  • The following code snippet shows the handleRecordSuccess function:
    function handleRecordSuccess(currentFilePath) {
  • The handleRecordSuccess function stores the recorded audio filepath in the "location" hidden field, which is used later by the playback button, and shows the "playSound" button.
  • In requestApplicationDirectory(callback), which is called in case of Android, it does the following:
    • Calls window.requestFileSystem in order to request the device filesystem before performing any file operation(s)
    • Calls fileSystem.root.getDirectory when the filesystem is ready in order to create our custom application directory
    • When our custom application directory is created successfully, the path of the created directory, or the existing directory, is passed to recordVoice() that was illustrated earlier
  • In the other application actions, the following code snippet shows the "stopRecordingSound" tapping and "recordSoundDialog" closing event handlers:
    $("#recordSoundDialog").on("popupafterclose", function(event, ui) {
    $("#stopRecordingSound").on("tap", function(e) {
    function stopRecordingSound(recordingCallback) {

In the "stopRecordingSound" tapping event handler, it closes the open "recordSoundDialog" pop up. Generally, if "recordSoundDialog" is closed by the "stopRecordingSound" button's tapping action or by pressing special device keys, such as the back button in Android devices, then the recording timer stops as a result of calling clearInterval(recInterval), and then it calls the stopRecordingSound() function to stop recording the sound.

The stopRecordingSound() function calls the Media object's stopRecord() method, and then releases it by calling the Media object's release() method. The following code snippet shows the "playSound" tap event handler:

var audioMedia;
var recordingMedia;

$("#playSound").on("tap", function(e) {

   var playCallback = {};

   playCallback.playSuccess = handlePlaySuccess;
   playCallback.playError = handlePlayError;

   playSound($("#location").val(), playCallback);

function playSound(filePath, playCallback) {
   if (filePath) {                

       audioMedia = new Media(filePath, playCallback.playSuccess,

       // Play audio;
function cleanUpResources() {
   if (audioMedia) {
       audioMedia = null;

   if (recordingMedia) {
       recordingMedia = null;

In the "playSound" tap event handler, it calls the playSound(filePath, playCallback) function by passing the audio file location, which is stored in the "location" hidden field and playCallback.

The playSound(filePath, playCallback) function uses the Media object's play() method to play back the saved audio file after releasing used Media objects. Note that this is a requirement to avoid running out of system audio resources.

Building and running Sound Recorder application

Now, after developing our application code, we can start building our application using the following cordova build command:

> cordova build

In order to run the application in your Android mobile or tablet, just make sure you enable USB debugging in your Android device. Then, plug your Android device into your development machine and execute the following command from the application directory:

> cordova run android

Congratulations! After running this command, you will see the Sound Recorder application deployed in your Android device; you can now start testing it on your real device.


In this article, you developed your first Apache Cordova application. You now know how to use the Apache Cordova Device API at a basic level. You also know how to use the Media and File APIs along with jQuery mobile to develop the Sound Recorder application. You now understand how to use Apache Cordova CLI in order to manage your Cordova mobile application. In addition, you know how to create a Cordova project, add a new platform (in our case, Android), build your own Cordova mobile application, and deploy your Cordova mobile application to the emulator, and most importantly, to a real device!

To learn more, refer to these books:

Resources for Article:

Further resources on this subject:

You've been reading an excerpt of:

JavaScript Mobile Application Development

Explore Title
comments powered by Disqus