I’m trying to dispatch an event from native java code to javascript environments to trigger some javascript functions. I tried using triggerJSEvent but to no success. I tried the official documentation, code from forum but they all won’t work.
The code:
@CapacitorPlugin(name = "TestEvent")
public class TestEvent extends Plugin {
Bridge myBridge;
@Override
public void load() {
myBridge = bridge;
}
@PluginMethod
public void testCall() {
/*
The problematic part:
*/
// A. As-is from official documentation (https://capacitorjs.com/docs/core-apis/android#triggerjsevent)
//bridge.triggerJSEvent("testEvent", "window", "{ 'testKey': 'dataValue' }");
// B. Creating a copy and referencing bridge from it (https://forum.ionicframework.com/t/capacitor-v3-plugin-addeventlistener-and-triggerjsevent-lacking-and-dont-work-as-described/206641/3)
myBridge.triggerJSEvent("testEvent", "window", "{ 'testKey': 'dataValue' }");
}
}
Here’s the error log:
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.getcapacitor.Bridge.triggerJSEvent(java.lang.String, java.lang.String, java.lang.String)' on a null object reference
at com.capacitor.reproduction.triggerJSEvent.TestEvent.testCall(TestEvent.java:31)
at com.capacitor.reproduction.triggerJSEvent.TestPlugin.testRun(TestPlugin.java:24)
at java.lang.reflect.Method.invoke(Native Method)
at com.getcapacitor.PluginHandle.invoke(PluginHandle.java:138)
at com.getcapacitor.Bridge.lambda$callPluginMethod$0(Bridge.java:774)
at com.getcapacitor.Bridge.$r8$lambda$ehFTi5f4HhVNFKTbCKAYDkpQYRA(Unknown Source:0)
at com.getcapacitor.Bridge$$ExternalSyntheticLambda3.run(Unknown Source:8)
at android.os.Handler.handleCallback(Handler.java:883)
at android.os.Handler.dispatchMessage(Handler.java:100)
at android.os.Looper.loop(Looper.java:237)
at android.os.HandlerThread.run(HandlerThread.java:67)
More information can be found in the bug report I created: bug: Capacitor listeners failing to be called from Android notifyListeners with foreground service · Issue #6234 · ionic-team/capacitor · GitHub
It seems like there’s a bug with that function or official documentation is wrong or outdated.
I literally searched everywhere to search for some example codes, but I couldn’t find much. These are some codes(reference) I’ve tried:
- Official documentation (Capacitor Android API | Capacitor Documentation)
- Capacitor V3: Plugin addEventListener and triggerJSEvent lacking and don't work as described - #3 by Daveshirman
Am I doing something wrong? Or is there a better/alternative way of calling a javascript function from native java code?