Capacitor V3: Plugin addEventListener and triggerJSEvent lacking and don't work as described

Capacitor V3:

I’m trying simply to send an event from Android to JS. My plugin is working so far otherwise.

Does anyone have a working example of just calling JS from Android, no params?

Both of the documentation below have issues when I try to follow either approach:

I’ve tried the following:

import { MyPlugin } from 'capacitor-plugin-myplugin';


MyPlugin.addEventListener('myEvent', () => { 
    // ....
})

But I get:

Property 'addListener' does not exist on type 'MyPlugin'.

If I extend my plugin class in the Java and do:

public class MyPlugin extends Plugin {
//....

then call:

bridge.triggerJSEvent("finishedPlaying", "window");

I get:

java.lang.NullPointerException: Attempt to invoke virtual method 'void com.getcapacitor.Bridge.triggerJSEvent(java.lang.String, java.lang.String)' on a null object reference

Hi,
I have exactly same problem. Have you found any solution?

Damn, this forum is like a graveyard sometimes. Either that or no one actually knows what they’re doing.

So yeah, I ended up doing the following:

  1. Override the load() function in your plugin class
  2. Store a reference to the bridge object
  3. Use that reference to call the trigger events instead.

e.g in your main plugin class:


public class MyPlugin extends Plugin {

    Bridge myBridge;


    @Override
    public void load() {   
        myBridge = bridge;
    }

    @PluginMethod
    public void someCall(PluginCall call) { 
        // do whatever you're doing.
        myBridge.triggerJSEvent(....)
    }

}
1 Like

I found another solution. I looked it up at the existing capacitor App plugin.
You have to extend your definition file.


import type { PluginListenerHandle } from '@capacitor/core';

export type ScanButtonPressedListener = () => void;

/**
   * Listen for scanButtonPressed
   *
   * @since 1.0.0
   */
  addListener(
    eventName: 'scanButtonPressed',
    listenerFunc: ScanButtonPressedListener,
  ): Promise<PluginListenerHandle> & PluginListenerHandle;

I am experiencing ‘addListener’ does not exist on plugin as well.

Property ‘addListener’ does not exist on type ‘MyPlugin’

Extending with Plugin interface provided by capacitor helps

import {registerPlugin} from "@capacitor/core";
import {Plugin} from "@capacitor/core/types/definitions";

export interface BleDemoPlugin extends Plugin{
  scanForReader(options: { value: string }): Promise<{ value: string }>;
}

Us Typescript lovers will do just fine reverting to the ancient days of Javascript by essentially telling our compiler, “hold my beer.”

const eventListener = await (MyPlugin as any).addListener('eventName', (eventData: any) => this.doThings(eventData) );