How to use cordova custom plugin in ionic

hi,
how to use cordova custom plugin in ionic 3.

how to import cordova custom plugin and how to call a method in ionic home.ts

2 Likes

Hi, @subbut

For, add your custom cordova plugin,

cordova plugin add "folder path of your custom plugin"

For, import cordova custom plugin,

declare var myPlugin: any;

For, call plugin method,

myPlugin.myFuntion((data) => {
        console.log(data);
},(err) => {
        console.log(err);
});

Thank you.

2 Likes

Hi addwebsolution,

i am new for ionic
 please help me

home.html file have this code:

<button class=“btn” (click)=“showToast()”>Toast Message

home.ts file this code:

import { Component } from ‘@angular/core’;
import { NavController } from ‘ionic-angular’;
import { Platform } from ‘ionic-angular’;
import { StatusBar } from ‘@ionic-native/status-bar’;
import { SplashScreen } from ‘@ionic-native/splash-screen’;
declare var Customplugin: any;
@Component({
selector: ‘page-home’,
templateUrl: ‘home.html’
})
export class HomePage {
constructor(private platform: Platform, statusBar: StatusBar, splashScreen: SplashScreen) {}
showToast(){
Customplugin.show((data) => {
alert(data);
},(err) => {
alert(err);
});
}

}

my cordova plugin folder name: cordova-plugin-customplugin

cordova plugin.xml:

<?xml version='1.0' encoding='utf-8'?>


Customplugin












package.json:

{
“name”: “cordova-plugin-customplugin”,
“version”: “0.0.1”,
“description”: “”,
“cordova”: {
“id”: “cordova-plugin-customplugin”,
“platforms”: [
“android”
]
},
“keywords”: [
“ecosystem:cordova”,
“cordova-android”
],
“author”: “”,
“license”: “ISC”
}

Customplugin.js:

var exec = require(‘cordova/exec’);

var Customplugin = function() {
console.log(‘Customplugin instanced’);
};

Customplugin.prototype.show = function(msg, onSuccess, onError) {
var errorCallback = function(obj) {
onError(obj);
};

var successCallback = function(obj) {
    onSuccess(obj);
};

exec(successCallback, errorCallback, 'Customplugin', 'show', [msg]);

};

if (typeof module != ‘undefined’ && module.exports) {
module.exports = Customplugin;
}

and Customplugin.java :

package cordova-plugin-customplugin;

import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.CallbackContext;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONArray;
import org.json.JSONObject;
import org.json.JSONException;
import android.content.Context;
import android.widget.Toast;

/**

  • This class echoes a string called from JavaScript.
    */
    public class Customplugin extends CordovaPlugin {

    @Override
    public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
    if (action.equals(“coolMethod”)) {
    String message = args.getString(0);
    this.coolMethod(message, callbackContext);
    return true;
    }
    if (“show”.equals(action)) {
    show(args.getString(0), callbackContext);
    return true;
    }
    return false;
    }

    private void coolMethod(String message, CallbackContext callbackContext) {
    if (message != null && message.length() > 0) {
    callbackContext.success(message);
    } else {
    callbackContext.error(“Expected one non-empty string argument.”);
    }
    }
    private void show(String msg, CallbackContext callbackContext) {
    if (msg == null || msg.length() == 0) {
    callbackContext.error(“Empty message!”);
    } else {
    Toast.makeText(webView.getContext(), msg, Toast.LENGTH_LONG).show();
    callbackContext.success(msg);
    }
    }
    }

when i run ionic serve show this bellow message:

Runtime Error:

Customplugin is not defined

Stack:

ReferenceError: Customplugin is not defined
at HomePage.webpackJsonp.194.HomePage.showToast (http://localhost:8100/build/main.js:64:9)
at Object.eval [as handleEvent] (ng:///AppModule/HomePage.ngfactory.js:17:27)
at handleEvent (http://localhost:8100/build/vendor.js:13608:172)
at callWithDebugContext (http://localhost:8100/build/vendor.js:15093:42)
at Object.debugHandleEvent [as handleEvent] (http://localhost:8100/build/vendor.js:14680:12)
at dispatchEvent (http://localhost:8100/build/vendor.js:10057:25)
at http://localhost:8100/build/vendor.js:10671:38
at HTMLButtonElement. (http://localhost:8100/build/vendor.js:36367:53)
at t.invokeTask (http://localhost:8100/build/polyfills.js:3:15660)
at Object.onInvokeTask (http://localhost:8100/build/vendor.js:4973:33)

Ionic Framework: 3.9.2
Ionic App Scripts: 3.1.8
Angular Core: 5.0.3
Angular Compiler CLI: 5.0.3
Node: 8.9.4
OS Platform: Linux 4.4
Navigator Platform: Linux x86_64
User Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.186 Safari/537.36

solve issue : declare let myPlugin: any;

I am glad that it has helped you, if this has solved your issue then you can always mark it as solution.

I am still getting
Customplugin is not defined error

Am I missing something else?

Gracias por esta respuesta, solo a partir de hoy e descubierto un poco mas este tema de los plugins con Cordova, mas específicamente a comprender q no es obligatorio utilizar los Ionic/native, entendiendo q’ tambn se pueden utilizar los plugins directamente en Ionic pero “apuntando” a cordova, utilizandolos con:

*declare let myPlugin: any;

Y esta esta manera llamar a los métodos q el plugin proporciona e igualmente todos las funciones q el mismo nos ofrece.

Creo q, no lo he probado aun, q cuando se va a llamar directamente a Cordova no es necesario instalar el plugin nativo de ionic.

Bueno muchas gracias y espero poder haber aportado algo de conocimiento.