--- title: Create plugin for Cordova tags: custom plugin, cordova description: Create plugin for Cordova --- # 建立自己的plugin@Cordova for iOS and Android --- ## 前置作業 - Android Studio or XCode ready. - Cordova project ready. - Node.js and npm ready. --- ## 安裝plugman ```typescript npm install -g plugman ``` --- ## 透過plugman建立plugin ```typescript plugman create --name CustomPlugin --plugin_id "cordova.plugin.customplugin" --plugin_version 0.0.1 ``` --- ## 加入plugin for android or iOS ```typescript cd CustomPlugin plugman platform add --platform_name ios ``` --- ## 建立package.json套件相關資訊 ```typescript= plugman createpackagejson . ```  --- ## 目錄架構 ```typescript CustomPlugin/ ├───src/ │ └───android/ │ └───CustomPlugin.java ├───www/ │ └───CustomPlugin.js ├───package.json └───plugin.xml ``` --- ## 加入plugin到專案中 先切換到Cordova專案platforms那一層 ```typescript cordova plugin add "plugin path" e.g. cordova plugin add "/Users/aa/Google Drive/Library/test/CustomPlugin" ```  --- ## 檢視plugin是否被加入專案中 1. CustomPlugin.java  2. CustomPlugin.js  3. cordova_plugins.js裡面是否有plugin資訊  --- ## 修改index.js ```javascript= var customPlugin = cordova.plugins.CustomPlugin; customPlugin.coolMethod("test Custom Plugin ok", function(data) { alert(data); }, function() { alert("Error calling Plugin"); }); ```  --- ## 增加其他method 1. 在CustomPlugin.js加上程式碼 ```javascript= exports.packageName = function (success, error) { exec(success, error, 'CustomPlugin', 'packageName', []); }; ```  2. 在CustomPlugin.java加上程式碼 ```java= else if (action.equals("packageName")) { callbackContext.success(cordova.getActivity().getApplicationContext().getPackageName()); return true; } ```  3. 在index.js加上程式碼 ```javascript= customPlugin.packageName(function(data) { alert(data); }, function() { alert("Error calling Plugin"); }); ```  --- ### 執行結果 + 成果1  + 成果2  --- ### 參考資訊 - [5分鐘創建Cordova Plugin教學](https://www.blogbrb.com/posts/skillshare/create-cordova-plugin-5-minutes/)
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up