Creating a Cordova Plugin for Windows
(Windows only) Create a bridge between a Windows and the Cordova plugin.
Cordova Plugin Architecture
A Cordova plugin contains at least three files: plugin.xml, common code, and platform-specific code. The plugin.xml contains some metadata about the plugin, such as its name and ID. You can use this metadata when you add the plugin to a Cordova project. You can also define the common parts of the plugin and copy any necessary resource files. This is an example of a plugin file structure:
C:\WORKS\TEST\SAMPLEPLUGIN | -- plugin.xml | -- README.md | -- src | -- windows | -- hello_proxy.js | -- www | -- hello.js
plugin.xml is located at the first level of the file structure, the common code is located in the www folder, and the platform-specific code is located in the windows folder.
Creating the plugin.xml File
<?xml version="1.0" encoding="utf-8"?> <plugin xmlns="http://www.phonegap.com/ns/plugins/1.0" id="com.sap.test.sample" version="1.0.0"> <name>Sample Plugin</name> <js-module src="www/hello.js" name="hello"> <clobbers target="sap.hello" /> </js-module> <platform name="windows"> <js-module name="hello_proxy" src="src/windows/hello_proxy.js"> <clobbers target="hello_proxy"/> </js-module> </platform> </plugin>
Creating Common Content
Create the common content that is used by all platforms. In this example, the code is saved in the hello.js file:
/*global cordova, module*/ module.exports = { sayHello: function (name, successCallback, errorCallback) { //The plugin calls the native (proxy) layer of the plugin cordova.exec(successCallback, errorCallback, "HelloProxy", "sayHello", name); } }; });
Creating Platform-Specific Content
The sayHello function in this sample calls the native layer of this plugin. In this example, the Windows-specific layer is in the hello_proxy.js file located in src\windows:
var exec = require("cordova/exec"); module.exports = { sayHello: function (successCallback, errorCallback, name) { try { var response = "Hello my friend, " + name; successCallback(response); } catch(err) { errorCallback(err) } } }; //The proxy will be available for the Cordova require("cordova/exec/proxy").add("HelloProxy", module.exports); });After the function finishes its task, the response is sent back by calling the given success callback. If any error happens, the caller is notified via error callback invocation.
Installing the SamplePlugin into a Cordova Project
- Create a new Cordova
project.
$ cordova create hello com.sap.test.sample
- Install the plugin.
$ cd hello $ cordova plugin add com.sap.test.sample --searchpath <path_to_plugin>
- Install
Windows.
platform cordova platform add windows
- Run the code.
cordova run