Monday, July 27, 2015

Cordova Plugin - Overview

A plugin is a package of injected code that allows the cordova web view within which the app renders to communicate with the native platform on which it runs. Plugins provide access to the device and platform functionality that is ordinarily unavailable to the web based applications. 

Plugin comprises of a single javascript interface along with corresponding native code libraries for each platform. In essence this hides various native code implementations behind a common Javascript interface. 

To make a simple plugin such as echo client, the steps are as below 

1. To Build Plugin 
Application can use CLI’s plugin add command to apply a plugin to a project. the argument to that is the URL to the git repository that contains the plugin code. 

e.g. 

cordova plugin add https://plugin.git 

The plugin repository features a plugin.xml file at the top-level. This is the manifest file for the plugin. The id attribute is the reverse dns name format of the package as the apps to they are added. the js-module tag specifies the common javascript interface. The platform tag specifies the corresponding platform code say for e.g. iOS platform. The platform tag has config-file and that encapsulates the feature tag that is injected into the platform-specific config.xml to make the platform aware of the additional code library. the header file and the source file for the library is specified in the header-file, source-file tags. 

The Javascript interface of the plugin

this is the most important part and is the front facing code interface to the plugin. It will have a cordova.exec function that communicates with the native platform. The syntax is below 

cordova.exec(function(winParam){},function(error){},”service”,”action”,[“firstArgument”,”secondArgument”,42,false]);

winParam){} => Is the success callback 
error){} => is the failure callback
“service” is the name of the service to call on the native side. 
“action” => is the name of the action to be called on the native side. 
arguments is the array of arguments to pass to the native side. 

window.echo = function (str,callback)
{
cordova.exec(callback,function(err) {callback (‘nothing to echo’);},”Echo”,”echo”,[str]);
};

this basically attaches the echo as a window function. The function accepts a string to be echoed and the callback function for the echo. 

The function can be called like the below 

window.echo(“echo me ”,function(echovalue){alert(echovalue==“echo me”)} );

references:

No comments:

Post a Comment