How to write Cordova Plugins

Cordova Plugins are one of the dark arts of hybrid app development, helping web apps running natively access the full power of the device underneath. Their obscurity separates the haves from the have nots, with whole swaths of Cordova users relying on a relatively small group of plugin developers to build and maintain these crucial pieces of functionality for their apps (like the famous Eddy Verbruggen).

It doesn’t have to be this way. More Cordova developers can and should venture into Cordova plugin development, because it’s not as hard as it’s cracked up to be, and the ecosystem needs more people to step in and help out.

At Ionic, we’ve identified the Cordova plugin ecosystem as one of the most important and at-risk parts of the Cordova experience, and we’re working hard to change that through education, maintaining existing plugins, and building new plugins that expand the capabilities and features of Cordova out-of-the-box.

Let’s start at square one and walk through the process of becoming a seasoned Cordova plugin developer. I think you’ll find that it’s much less intimidating than it seems!

0. What is a Cordova plugin?

Before we get into building our first Cordova plugin, let’s take a step back and talk about what a Cordova plugin, and, by extension, Cordova is.

Cordova is a set of command line tools and a plugin bridge for building native apps for the app stores that lets us build our app in a web view, and call native code from JavaScript. When we install Cordova on our computer, we’re installing a set of tools that helps package up this web content, place it into a native app container, deploy it to a device or simulator for testing, and build binaries for final release to the app store.

Inside of that container is a relatively small bridge that transports certain JavaScript calls we make into corresponding native code to give our app the ability to do complex, native things, that aren’t baked into the standard Web APIs.

Building Cordova plugins means we are writing some JavaScript to call down to some Native (Obj-c/Swift, Java, etc.) code we also write, and returning the result to our JavaScript.

To sum it up: we build a Cordova plugin when we want to do something natively that doesn’t yet have a Web API analog, like accessing HealthKit data on iOS or using the Fingerprint scanner on Android.

1. Getting started: scaffolding our first plugin

Plugins plugins everywhere, but how do we start our own? There are two ways to do this: we can use the plugman tool to create one quickly, or we can get all mitosis on an existing plugin by cloning it.

Generally, I prefer cloning existing plugins because you get a faster start with code filled in for all the platforms you want. I’ve cloned the Cordova Device plugin as it’s rather simple, but recently we released a Cordova Plugin Template which comes pretty bare bones. Let’s git clone the template.

We see a few files and directories here, but most importantly: plugin.xml, src, and www:

plugin.xml is one of the most important files here. It’s what Cordova parses to figure out what platforms your plugin supports, preferences it has that the user can configure, source files we’ll include in our final app build, and more. It’s also a bit esoteric so generally we’ll look at other plugin.xml files and use our Computer Science background to copy and paste into ours.

Next is src. This is where our native code lives. If we peek into here we see an ios and android folder.

Finally, www is where the JavaScript code for our plugin lives. This is what gets called first and then kicks off Cordova to call our native code.

Let’s go ahead and copy all the files and directories from the template we cloned to a new directory where we are going to work on our plugin. For this tutorial, we will be creating a simple “echo” plugin, so we can create an echo-plugin directory.

2. Configuring our Plugin

Now for my favorite part: writing XML!!!1

Okay, it’s not glamorous but the plugin.xml file is where everything happens and it’s where we should start. First, we need to give our plugin a unique name and id. As far as naming conventions go, the id is usually of the form this-is-a-plugin, like cordova-plugin-device (as an example):

Next, we’ll set a reference to our JavaScript code:

At a glance, js-module specifies the JS code that will run, and <clobbers> sets what window variable the plugin will be exported under. So, in this case, our script file is www/plugin.js, and when our app runs, we’ll be able to access the plugin at window.MyCordovaPlugin.

Next, we specify the platforms we are going to support, along with references to the corresponding native code for each, starting with Android:

Inside of <config-file> we specify our Android package name and also the symbol Cordova will use to identify our plugin, in this case it’s MyCordovaPlugin. Finally, we have a reference to our main Java code inside of <source-file> which is where our native code lives.

Let’s take a look at ios:

In this snippet, we see much of the same stuff from Android. Inside of <config-file> we have a similar entry to Android just without the Java package format. Finally, we list out the source files Cordova will copy into our app before build, making sure to specify both header and source files we will include. Note: plugins can be built in Swift, but given that Cordova is still in Objective-C and there’s a little overhead to using Swift, we’re going to focus on Objective-c for now.

3. Building our plugin: JavaScript

Let’s start with the JavaScript API that we’d like to expose to the developer. In this case, our JavaScript code lives in www/plugin.js. Here’s what it looks like:

In this case, we have a simple object that has echo and getDate as functions the developer can call. When run, the developer can call this plugin by writing

window.MyCordovaPlugin.echo(‘Hello!’, function() { //callback })

The code that does the magic here is the exec function we’ve imported from cordova/exec. When called, this plugin tells Cordova’s plugin layer to find the plugin identified by PLUGIN_NAME and send the action passed in to either a function call (iOS) or a switching function (android). It’s a good practice to make sure the Cordova symbol name we give our plugin (in this case MyCordovaPlugin) matches the <clobbers target> setting from our plugin.xml, as that will be the window variable we access.

For many plugins, this is as complex as they’ll need to get on the JavaScript side, as the native code is doing all the work. However, I implore future Cordova plugin developers to strongly consider doing more of the actual grunt work in JavaScript instead of Native code. For example, avoid things like String processing, JSON encoding, etc. in Native code because you’d have more platform-specific code to maintain, and often JavaScript performs these tasks with much less mental overhead for the developer (read: string processing in Objective-C is agonizing as all hell). Here’s one of our plugins that does a lot of cross-platform work in the JavaScript layer, only using the Native layer to get data the JS layer can’t.

4. Building our plugin: Native iOS

Now for the fun part: writing some native iOS Objective-C code.

Let’s start with the Objective-C header file, in src/ios/MyCordovaPlugin.h:

This header file is a spec of the functions we’ll implement in our corresponding .m, MyCordovaPlugin.m:

These methods are called through Cordova when we run exec() from our JavaScript. They take a CDVInvokedUrlCommand* argument that contains the arguments we passed from JS, along with a reference to the callback the user passed. We can configure the callback to only work once, or to be called repeatedly (by using [result setKeepCallbackAsBool]).

Once in this method, we’re doing plain ol’ Objective-C. Anything you can dream of doing natively you can do here. When you’re done and want to return data back to JS, create a CDVPluginResult object and send it to the commandDelegate which dispatches the result back to JS.

In the example above, the echo method just calls NSLog to echo the string the user passes, while getDate gets a native date from iOS and then converts it into an ISO string and returns it.

This is by no means an exhaustive intro to building iOS Cordova plugins. The best way to go from here to building complex plugins is to study existing ones, like the Geolocation plugin.

5. Building our Android plugin

Building the Android part of our plugin is exactly the same conceptually, but Android plugins have slightly different semantics. Here’s what our src/android/com/example/ looks like:

For Android, we have one single execute method that Cordova calls with the action we put into exec() on the JS side, along with the arguments and callback context. Thus, instead of having Cordova call our method directly, we have to check the action string against each action name we support, in this case “echo” and “getDate”. Then, we perform the action and return the result just like on the iOS Side.

Again, to see a more complex Android plugin, take a look at the Geolocation plugin source.

6. Testing plugins

Smashing our keyboard and producing code is the easy part. Now, we need to test and verify our plugin actually works.

To test a Cordova plugin, we need to have a Cordova/PhoneGap/Ionic app to run. Cordova plugins are not runnable on their own.

Assuming we have an existing Cordova app, we can add our plugin locally:

cordova plugin add --link ~/git/echo-plugin

The link flag adds our plugin as a symbolic link, meaning we can work on our code (at least the native code) and rebuild and run our app without having to add the plugin again. However, for some reason, the JavaScript side of our plugin doesn’t automatically update. As we build and modify the JS side, we have to remove the plugin quick using cordova rm my-cordova-plugin and add it back like we did before.

To test the plugin, we just run our app like normal, using our standard Cordova debugging techniques (attach browser dev tools, use IDE console, etc.).

If something ever gets wonky or out of sync, just try removing the plugin and adding it back. If that doesn’t work, remove your platform directory and make sure all references to your plugin are gone from the plugins directory. This tends to happen if you change things like the plugin id or name.

7. Where to go from here

This post was meant to lay out the basics of building a plugin. Day-to-day there isn’t much more beyond what I’ve written here, except lots more native code to do whatever fancy schmancy thing we’re trying to do.

If you’d like to dig in a bit from a slightly more practical angle, I’ve put together a Cordova Plugin Development Guide that runs through building the plugin above and the commands you’d use to add it to your project and test it, along with some advanced topics towards the end.

Whenever I build a Cordova plugin, I’m always amazed at how straightforward it is. For some reason, it always seemed like an incredibly unapproachable topic full of undocumented magic that only a few people knew. That’s not at all the case, and I hope this post encourages more people to try building their own plugins, or improving the ones that already exist out there.

Happy hacking!