Custom Capacitor 5 native plugin example

I have worked on creating own native Capacitor plugin fot Android/IOS and WEB enviroment with Ionic7/Angular setup. The typical tutorials are for version 4 and later. There are a few things I would that confuses me.

Plugin files:
definitions.ts // include the list of function promise definitions
‘’’
export interface MyCustomPlugin {
echo(options?: { value: string }): Promise<{
value: string; }>;
‘’’
index.ts //defines plugin import name and routes definitions to app
‘’’
import { MyCustomPlugin } from ‘./definitions’;
declare const MyCustom: MyCustomPlugin;
export * from ‘./definitions’;
export { MyCustom };
‘’’

web.ts // code that is used with web enviroment
‘’’
import { WebPlugin } from ‘@capacitor/core’;
import type { MyCustomPlugin } from ‘./definitions’;

export class MyCustomWeb extends WebPlugin implements MyCustomPlugin {
constructor() {
console.log(‘MyCustomWeb constructor’);
super(
{
name: ‘MyCustomWeb’,
platforms: [‘web’,‘android’,‘ios’]
}
);
}
async echo(options?: any) {
if(!options){console.log(‘ECHO test’);
return ‘ECHO test’;}
else{
console.log(‘ECHO’, options);
return options+options;
}
}
const MyCustom = new MyCustomWeb();
export { MyCustom };
‘’’

include in the Angular app:

page.html
‘’’
<ion-input [(ngModel)]=“test”>
<ion-button (click)=“tryNativePlugin()”>test Native Plugin

{{test}}

'''

page.ts:
‘’’
import { MyCustom } from ‘my-custom-plugin’;

public test= ‘’;

//this is executing MyCustom plugin web-echo-function
public async tryNativePlugin() {
let testVar = await MyCustom.echo({ value: ‘test’ });
console.log(‘testVar: ‘, testVar);
this.test = testVar.value;
}
‘’’
Pushing “test native plugin” -button just makes error:
‘’’
ERROR Error: Uncaught (in promise): TypeError: Cannot read properties of undefined (reading ‘echo’)
TypeError: Cannot read properties of undefined (reading ‘echo’)
‘’’

Have you installed plugin in your Ionic angular app?

For Plugin android path
…\android\src\main\java\com\techbinomial\plugins\mycustomplugin \yourpluginplugin,java

Check if pluginMethod is properly implemented.

e.g
@PluginMethod()
public void testPluginMethod(PluginCall call) {
String value = call.getString(“msg”);
JSObject ret = new JSObject();
ret.put(“value”,value);
call.resolve(ret);
}

In Ionic angular app’s MainActivity.java file register the plugin

public class MainActivity extends BridgeActivity {
@Override
public void onCreate(Bundle savedInstanceState) {

    registerPlugin(MyCustomPluginPlugin.class);  
    super.onCreate(savedInstanceState);   
}

}

If issue persists then check tutorials on TechBionomial channel.

Hi,
your video for making custom plugin was awesome. My problem was that that “npm run build” was not executed. Also some smaler mistakes were found. That video is the best tutorial for capacitor 5 -plugin creating I have found.

Thanks for support!

1 Like