How to create a Cordova Plugin from scratch
May 12, 2023 by Marvin

How to Create a Cordova Plugin from Scratch and integrate it into your App

What is a Cordova Plugin anyway?

Cordova Plugins provide the ability to use native device capabilities that are not available in pure web apps. Common examples are alert dialogs, toasts, camera access and many more. There are already a lot of ready to use plugins available: Cordova Plugins.

If there is no plugin available which helps you acquire the native functionality you need for your app or if you need to develop a Cordova Plugin as part of your product like we do, we have a solution. This article will serve you as a Cordova Plugin development tutorial on how to create a plugin by developing a plugin that will show an alert dialog.

Check out our Docutain SDK
Integrate high quality document scanning, text recognition and data extraction into your apps. It will soon be available as Cordova Plugin. To learn more about the Docutain SDK and its packages contact us at SDK@Docutain.com.

Prerequesites

  • Native Android development
    • Cordova Android SDK
  • Apache Cordova
  • Node.js

Create a Cordova Test Project

To test your plugin, create a Cordova project and integrate the plugin using the “Cordova create” command.

If you haven’t done already, you need to install Node.js and the Cordova CLI. To install the Cordova CLI, type the following command into a command shell after you have installed Node.js.

npm install -g cordova

Navigate to your working directory in the command line (Cordova CLI). In this example, we name the project AlertPluginTest and set it up as follows:

cordova create alert-plugin-test com.example.alertplugintest AlertPluginTest

Navigate to the project directory and add an Android dependency.

cd alert-plugin-test
cordova platforms add android

Executing this command will install all necessary prerequisites to run your Cordova Test Project on Android. Before you test the application, ensure that you meet all requirements. You can do so by executing the following command in your alert-plugin-test directory:

cordova requirements

Test the Cordova Test Project

Before we proceed with the actual plugin project, we need to make sure that our test app runs properly on Android. You can either run the app on a virtual device (emulator) or a real device. If you like to run the application on a virtual device, make sure you have installed one and it is running.

For Android you can follow this guide: Create a virtual device.

If you have installed it, make sure to run it via Android Studio. You should see a screen similar to this:

Android virtual device emulator Cordova Plugin

If you want to test your app on a real device, ensure that you connect it to your development machine.

To run the Test App you need to build it first:

cordova build android

Once the build has finished successfully, you can run the app either on your virtual device or your real device.

Run on a virtual device (emulator):

cordova emulate android

Run on a real device:

cordova run android --device

When the Cordova application is running, you should see something similar to this:

Android virtual device emulator Cordova Plugin

That’s it! Now we can proceed with the fun part.

Create the Plugin Project

In this example we name the plugin AlertPlugin. For the plugin project we need a folder with this name in your working directory, so create it:

cd ..
mkdir AlertPlugin

Navigate to this new folder and create a new file called plugin.xml:

cd AlertPlugin
type NUL > plugin.xml

Copy the following content into the plugin.xml file and save it:

<plugin xmlns="http://apache.org/cordova/ns/plugins/1.0"
        xmlns:android="http://schemas.android.com/apk/res/android"
        id="cordova-plugin-alertplugin" version="0.0.1">
    <name>AlertPlugin</name>
    <description>A Cordova plugin for Android that allows users to display simple alert dialogs.</description>
    <license>MIT</license>
    <keywords>cordova,android,dialog,alert</keywords>
    <repo>https://github.com/your_repository_here</repo>
    <issue>https://github.com/your_issues_url_here</issue>
    <engines>
	<engine name="cordova" version=">=3.0.0"/>
    </engines>
    <js-module src="www/alertplugin.js" name="alertPlugin">
	<clobbers target="window.plugins.alertPlugin" />
    </js-module>
    <platform name="android">
	<config-file target="res/xml/config.xml" parent="/*">
		<feature name="AlertPlugin">
			<param name="android-package" value="com.test.cordova.plugin.AlertPlugin"/>
		</feature>
	</config-file>
	<source-file src="src/android/AlertPlugin.java" target-dir="src/com/test/cordova/plugin" />
    </platform>
</plugin>

What is the plugin.xml anyway?

The plugin.xml file is the base of your Cordova file Plugin. It provides a name for the plugin, the license you wish to use, links to the JavaScript source code that connects the plugin to the Cordova Project and much more. If you like to learn more, check out Cordova’s documentation.

The next file you need is the package.json file. It is the npm registry file that combines standard npm attributes with Cordova specific attributes. Create the file:

type NUL > package.json

Copy the following content into the package.json file and save it:

{
  "name": "cordova-plugin-alertplugin",
  "version": "0.0.1",
  "description": "A Cordova plugin for Android that allows users to display simple alert dialogs.",
  "cordova": {
    "id": "cordova-plugin-alertplugin",
    "platforms": [
      "android"
    ]
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/your_repository_here"
  },
  "keywords": [
    "Dialog",
    "Notification",
    "Message",
    "Alert",
    "ecosystem:cordova",
    "cordova-android"
  ],
  "engines": [
    {
      "name": "cordova",
      "version": ">=3.0.0"
    }
  ],
  "author": "Your Name ",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/your_github_issues_url"
  },
  "homepage": "https://your_homepage"
}

Build the JavaScript Bindings

Create a directory in your AlertPlugin root directory called www and in that directory create a new file called alertplugin.js:

mkdir www
cd www
type NUL > alertplugin.js

This JavaScript file defines the API that a Cordova Project uses to communicate with the plugin. Add the following code to your alertplugin.js:

// Empty constructor
function AlertPlugin() {}

// The function that passes work along to native shells
// Title and Message is a string
AlertPlugin.prototype.show = function(title, message, successCallback, errorCallback) {
  var options = {};
  options.title = title;
  options.message = message;
  cordova.exec(successCallback, errorCallback, 'AlertPlugin', 'show', [options]);
}

// Installation constructor that binds AlertPlugin to window
AlertPlugin.install = function() {
  if (!window.plugins) {
    window.plugins = {};
  }
  window.plugins.alertPlugin = new AlertPlugin();
  return window.plugins.alertPlugin;
};
cordova.addConstructor(AlertPlugin.install);

This code consists of two essential parts. The first part is the show method that will show a simple alert dialog containing the provided title and message. The second part is the installation constructor which binds the AlertPlugin to the window element.

Implement AlertPlugin for Android

Now, implement the Android code that displays the alert dialog after defining the API. At this point, we assume that you are familiar with the Android platform and know how to program for Android.

Create a src folder in your AlertPlugin directory. Inside src create an Android folder. Inside the Android folder create a new file called AlertPlugin.java:

cd ..
mkdir src
cd src
mkdir android
cd android
type NUL > AlertPlugin.java

Copy the following content into the AlertPlugin.java file and save it:

package com.test.cordova.plugin;
// The native alert dialog API
import android.app.AlertDialog;
// Cordova-required packages
import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.PluginResult;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class AlertPlugin extends CordovaPlugin {
  @Override
  public boolean execute(String action, JSONArray args,
    final CallbackContext callbackContext) {

    // Verify that the user sent a 'show' action
    if (!action.equals("show")) {
        callbackContext.error("\"" + action + "\" is not a recognized action.");
        return false;
    }

    String message;
    String title;
    try{
        JSONObject options = args.getJSONObject(0);
        message = options.getString("message");
        title = options.getString("title");
    } catch (JSONException e) {
        callbackContext.error("Error encountered: " + e.getMessage());
        return false;
    }       

    AlertDialog.Builder builder = new AlertDialog.Builder(cordova.getActivity());
    builder.setMessage(message).setTitle(title);
    AlertDialog dialog = builder.create();
    dialog.show();

    // Send a positive result to the callbackContext
    PluginResult pluginResult = new PluginResult(PluginResult.Status.OK);
    callbackContext.sendPluginResult(pluginResult);

    return true;
  }
}

Test your AlertPlugin

Now it is time to test your plugin. In order to do this, you need to install the plugin in your previously created test project.

Navigate to the root directory structure of your test project:

//if you have followed along, this should send you back to your working directory
cd ../../..
cd alert-plugin-test

Install the plugin by providing the path to the root directory of your plugin:

cordova plugin add ..\alertplugin\

Make sure that the last part of the command points to the root directory of your plugin code project.

After successfully installing the plugin, write some code to call it and display an alert dialog. To do so, open the index.js file which you can find in the www/js folder inside your test project directory. Add the following commands of code inside the onDeviceReady() method and save the file:

window.plugins.alertPlugin.show('Hello', 'I am a native Android alert dialog.', function() {
    console.log('We have a success!');
    }, function(err) {
    console.log('There was an error: ' + err);
});

Now it is time to run the app and see your plugin in action.

Run on a virtual device (emulator):

cordova emulate android

Run on a real device:

cordova run android --device

Once the app has started, you should see an alert dialog similar to this:

Android virtual device emulator Cordova Plugin

Check out our Docutain Cordova Scanner SDK
Integrate high quality document scanning, text recognition and data extraction into your apps. It will soon be available as Cordova Document Scanner Plugin. To learn more about the Cordova Document Scanner SDK or the Docutain SDK and its packages, contact us at SDK@Docutain.com.

Congratulations! You now know the basics of how to create Cordova plugin. If you enjoyed this Cordova tutorial we appreciate you sharing it among your colleagues, partners and friends.

Your contact to Docutain

Please tell our colleague Harry Beck how the Docutain SDK can help you with your project. We are looking forward to receiving your inquiry, either by telephone or contact form.