JavaScript Plugins for Cordova

The more I delve into the inner workings of Cordova, the clearer it becomes to me. Yet, one area that continues to perplex me is the structure of JavaScript plugins.

Typically, I write my JavaScript code as follows, adhering to what I believe is the standard convention:

(function () {
    var version = "EXAMPLE",
        v1,
        v2,
        v3
        res;

    function somePrivateFunction(successCallback, errorCallback) {
        someOtherPrivateFunction(sc, ec);
    }

    function someOtherPrivateFunction(successCallback, errorCallback) {
        cordova.exec(sc, ec, 'SomeService', 'SomeMethod', [args]);
    }

    res = {
        VERSION: version,
        doSomething: function (sc, ec) {
            somePrivateFunction(sc, ec);    
        }
    }

    window.myPlugin = res;
}());

However, I have noticed that Cordova employs a format with which I am completely unfamiliar. It seems to utilize something referred to as require, based on the declarations in most plugins.

The format commonly used in official Cordova plugins appears like this:

    var argscheck = require('cordova/argscheck'),
    utils = require('cordova/utils'),
    exec = require('cordova/exec');

var myPlugin = function () {

}

myPlugin.doSomething = function(successCallback, errorCallback) {
    exec(successCallback, errorCallback, 'SomeService', 'SomeMethod', [args]);
}

myPlugin.doSomethingElse = function(successCallback, errorCallback) {
    exec(successCallback, errorCallback, 'SomeService', 'SomeOtherMethod', [args]);
}

modules.export = myPlugin;

This approach involving require library is confusing to me as I lack knowledge in this area. It feels entirely foreign in terms of JavaScript.

I'm puzzled by concepts such as modules, the cordova/[...] syntax, and their significance. Where are these other cordova modules specified and what is the role of modules?

Moreover, can someone explain the purpose of modules.export? I find it challenging to grasp the <js-module> tag in the plugin.xml and the <clobbers> tag while struggling with this aspect.

It's my understanding that Cordova includes cordova.define around the plugin during project compilation.

If anyone could shed some light on this, I'd greatly appreciate it!

Answer №1

the require and exec functions are methods of the cordova object. When a plugin is installed, it is wrapped in a function that grants access to the cordova object. These calls are known as cordova.require and cordova.exec,

Here is an example of what a plugin js file looks like before and after installation:

BEFORE:

var exec = require("cordova/exec");

var VideoPlayer = {
    play: function(url) {
        exec(null, null, "VideoPlayer", "playVideo", [url]);
    }
};

module.exports = VideoPlayer;

AFTER:

cordova.define("com.dawsonloudon.videoplayer.VideoPlayer", function(require, exports, module) {

    var exec = require("cordova/exec");

    var VideoPlayer = {
        play: function(url) {
            exec(null, null, "VideoPlayer", "playVideo", [url]);
        }
    };

    module.exports = VideoPlayer;

});

In addition, regarding the configuration setup, the clobbers command helps to protect the namespace of your plugin object. Here's an example from my own plugin:

<js-module src="www/VideoPlayer.js" name="VideoPlayer">
    <clobbers target="VideoPlayer" />
</js-module>

This indicates the name of my JS file and the object namespace used for calling my plugin in JS.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

I am facing an issue where both curl and file_get_contents are not functioning properly after

When attempting to access a user's city information using coordinates, I have encountered an issue with the response not being displayed in my console. The process involves a javascript function that takes latitude and longitude data, sends it to a PH ...

Changing a JavaScript string into an array

I have extracted an array of objects from a hidden HTML input field and received the following string: "{"id":"1234","name":"john smith","email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="dab0a9b7b3aeb29ab8b6bbb2f4b9b5b7" ...

Attempting to trigger an action from a Vuex module proves futile as the error message "[vuex] unknown action type" is generated

I've been struggling to successfully register a Vuex module. Below is the code I've been working with: stores/index.js: import Vuex from 'vuex'; import resourcesModule from './resources'; import axios from '@/helpers/ax ...

Updating or adding items to an array using underscore library

A scenario involves an object with incoming data and an array that contains saved data. The goal is to check if the "cnName" from the new data already exists in the "savedData" array. If it does, then the object in "savedData" should be replaced with the n ...

JavaScript Discord bot encounters an issue: .sendMessage function is not recognized

Currently, I am developing a bot and testing its messaging functionality using .sendMessage method. (I prefer the bot not to send messages upon receiving any input, hence avoiding the use of: bot.on("message", function(message) {}); However, I am encoun ...

What is the best way to query based on a nested object property in Mongoose?

const collection = [ { inner_obj: { prop: "A" } } ] Get the outer records by searching for the ones that match the value of the `prop` property within the `inner_obj` column. How can we locate the o ...

Guide to Retrieving 'req' in JavaScript within Node.js / Express Framework

I have a loaded page named tournament/:key, where a Tournament object is passed. The Jade template accesses variables from the Tournament using syntax like #{tournamentData.name} to display the data on the page. The list of matches is stored as an array wi ...

Getting the (x,y) Coordinate Value from jQuery Script and Saving it as a NSString

div tag is essential for applying bold, italic, and various other formatting options in UIWebview. My goal is to retrieve the position coordinates when a user interacts with the div tag using JavaScript/jQuery. I stumbled upon the required code on JSFiddl ...

Is the z-index feature not functioning as anticipated?

I'm currently working on a project involving a book that flips on click on both sides. The process involves checking the direction when a page is clicked and flipping it to the left if it's not to the right. Additionally, I adjust the z-index to ...

Can anyone provide a solution for determining the number of active intervals in Javascript?

Similar Question: How to View All Timeouts and Intervals in JavaScript? I've been working on an HTML5 game that includes a lot of graphical effects using intervals created by the setInterval function. However, I've noticed that my game is ru ...

Using anchor tags to send HTML code through email

I currently have an anchor tag on my website that looks like this: <a href="mailto:<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="7e0d11131b11101b3e0d11131b09161b0c1b501d1113">[email protected]</a>?subject=Wel ...

Using caret range and package-lock.json to acquire the most recent non-disruptive versions

I understand the purpose of package-lock.json, but I'm unsure about how the caret range works after adding this file. Let's say I have a package called my-module and I want to automatically receive all new non-breaking versions without manually ...

Modifying css background in real-time based on the current weather conditions

Is there a way to dynamically change the background image in CSS based on the weather condition? I'm utilizing the wunderground API to retrieve the weather data, which is stored in the weather variable. I am struggling with how to update the backgrou ...

Differences in SVG rendering between Chrome and Firefox

I am eager to create a diagram on my website using SVG. To ensure the diagram is displayed in full screen, I am utilizing availHeight and availWidth to determine the client screen's height and width, then adjust the scaling accordingly. My current sc ...

Is it possible to utilize a slot within a Vue.js loop?

I am encountering an issue with a template that is utilizing v-for to loop through. The template includes a named slot where the name is dynamically assigned within the loop. However, no content is displaying as expected. Can someone help me identify wha ...

Master the art of animating ng-view transitions with AngularJS

I have 2 distinct HTML pages, namely welcome.html and login.html. These two pages are incorporated or "inserted" into a common page called index.html through the utilization of an exclusive attribute known as ngview, together with a router provider. This i ...

Setting a cookie in a browser using an AJAX response: A step-by-step guide

When utilizing a Javascript function with jQuery to send a POST request to a web service, the response from the web server includes a header "Set-Cookie: name=value; domain=api.mydomain.com; path=/", along with a JSON body. However, despite this expected ...

How can I utilize match props in React JS with the Context API?

Currently working on a basic application that utilizes context API, fetch, and react hooks for all components except the context API component due to ongoing learning of hooks. The challenge lies in incorporating the match prop within the context API prov ...

Determine the selected option in the dropdown menu upon loading the page and when clicked

I am working on capturing the value of a drop-down list whenever it is changed or when the page loads. The aim is to display different div elements based on the selected option in the report field - either State or Year. Any assistance with this would be ...

How can I add a channel to a category using await(discord.js)?

Having trouble organizing a new channel within a category. The .setParent(categoryID) method seems to only work with existing channels, causing an issue when I attempt to execute my code. Take a look at the code snippet below: client.on("message" ...