In the event where you want to extend the Nebula for additional functionality to support your Javascript code, you can easily do so by adding a custom plugin
Let us create a simple JS API called addition
, it takes two parameters a
and b
, and return the sum of the two.
AlipayJSBridge.call("addition", {
a: 1,
b: 2
}, function(result) {
console.log(result.sum); // expect 3
});
First we need to create a new class and extend it from H5SimplePlugin
public class MyPlugin extends H5SimplePlugin {
}
Implement the onPrepare()
method, this is where we register the custom plugin to addition
event
@Override
public void onPrepare(H5EventFilter filter) {
List<String> list = new ArrayList<>();
list.add("addition");
filter.setEventsList(list);
}
Then we need to handle this event by implementing handleEvent()
method, please note that we do not implement interceptEvent()
here because the addition
event is to be consumed inside this plugin without further propagation. To learn the difference between handleEvent()
and interceptEvent()
, please click here.
@Override
public boolean handleEvent(H5Event event, final H5BridgeContext bridgeContext) {
// Get the JS API action name from event
String action = event.getAction();
if ("addition".equals(action)) {
additionInternal(event, bridgeContext);
}
// Return true since this event is to be consumed in this class
return true;
}
The core business logic is implemented in the additionInternal()
method.
private void additionInternal(H5Event event, final H5BridgeContext bridgeContext) {
if (event == null) {
return;
}
// Retrieve a and b from event param
JSONObject params = event.getParam();
int a = params.getIntValue("a");
int b = params.getIntValue("b");
// Perform addition
int sum = a + b;
// Construct the result object
JSONObject result = new JSONObject();
result.put("sum", sum);
// Send the json result to Javascript
bridgeContext.sendBridgeResult(result);
}
And that is it. Congratulations! you just create a very first custom JS API plugin. You can create as many plugins as you need to support your growing business.