我需要将数据/对象从 Cordova 插件发送回主 Cordova 视图。这是为了更改 ActionBar 标题等。
要走的路是什么?
返回PluginResult是可接受的方法。您的方法的成功回调将使用您通过 PluginResult 发回的数据调用。
我已经编写了工作代码来将数据从 Cordova 发送到 CordovaPlugin,反之亦然。
安卓代码
public class CustomPlugin extends CordovaPlugin {
@Override
public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
Log.d(TAG, action); //doPluginAction is printed
Log.d(TAG, args.getString(0));//parameter is printed
PluginResult result = new PluginResult(PluginResult.Status.OK, "here you can also send you message to app from plugin"); // You can send data, String, int, array, dictionary and etc
result.setKeepCallback(false);
callbackContext.sendPluginResult(result);
return true;
}
}
iOS 代码
//CustomPlugin.h file
#import <Cordova/CDVPlugin.h>
#import <Foundation/Foundation.h>
@interface CustomPlugin : CDVPlugin
-(void) doPluginAction:(CDVInvokedUrlCommand*) command;
@end
//CustomPlugin.m file
#import "CustomPlugin.h"
@implementation CustomPlugin
-(void) doPluginAction:(CDVInvokedUrlCommand*) command {
CDVPluginResult* result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:"here you can also send you message to app from plugin"];// You can send data, String, int, array, dictionary and etc
[self.commandDelegate sendPluginResult:result callbackId:command.callbackId];
}
@end
插件js文件的代码
www/CustomPlugin.js
var exec = require('cordova/exec');
exports.callPluginMethod = function (parameter, success, error) {
exec(success, error, “CustomPlugin”, "doPluginAction", [parameter]);
};
调用插件和完成块处理:
cordova.plugins.CustomPlugin.callPluginMethod("parameter", (success: any) => {
console.log(success);
},
(error:any) => {
console.log(error);
})