Determining installed plugins at runtime for Cordova and PhoneGap applications

Earlier today on Twitter a user asked an interesting question: How can I tell - via JavaScript - if a particular plugin is installed in a Cordova/PhoneGap application. I responded by asking how you wouldn't know since it is your own app, but then he mentioned that his code base was stand alone and would be used within other projects. (So basically - just JavaScript code that other Cordova/PhoneGap applications would use.)

There are a couple of different ways to handle this. The first, and simplest, is to look for the "hook" the plugin adds. For example, the barcode plugin adds methods to a cordova.plugins.barcodeScanner object. It would be trivial to see if that exists. Cool, problem solved, right?

Well in his case he was using InAppBrowser. This plugin simply modifies so it isn't something you can really (as far as I can see) introspect. I did some more digging and found something interesting.

If you look at the platform build version of your www code, you will notice it includes a cordova_plugins.js file:

If you open it up, you will see a list of any plugins you have installed. I opened up cordova.js (honestly, I don't look at it often, but I should) and saw that cordova_plugins.js was being loaded in dynamically and parsed. My assumption is that this has to happen before deviceready fires so you can safely use any plugins you've got installed. On a whim then I tried the following code inside my deviceready:

var md = cordova.require("cordova/plugin_list").metadata;

The metadata part came from what I saw in cordova_plugins.js. While the rest of the file has random stuff based on the plugins installed, metadata appears to be just a list of your plugins. I confirmed that this worked well:

So - that's it. I should note that I spoke with Shazron and he mentioned that if you used browserify, it might mess with how the JS file is generated. I'd say use with caution and let me know (via the comments) how it works for you.

Like This?

If you like this article, please consider visiting my Amazon Wishlist or donating via PayPal to show your support. You can also subscribe to the email feed to get notified of new posts.