我必须创建一个插件来捕获我的 iOS 应用程序的 Cordova webView 中发生的事件,并在应用程序的本机部分触发操作,反之亦然。
我已按照本教程进行操作,并且效果很好。
当我尝试将它调整到另一个应用程序时(我希望它比教程更通用),它可以从 webView 到本机部分,但不是相反。
我只是想单击导航栏上的按钮来更改我的 webView 的背景颜色。目前,插件的javascript代码似乎没有收到事件,因为只显示了iOS日志。
我所有的代码都在 XCode 中,所以我看不到来自 Web 部件的任何警告/错误。
这是插件的iOS部分:
@interface HybridBridge()
@property (nonatomic, retain) NSString *listenerCallbackId;
@end
@implementation HybridBridge
-(void)bindAction:(CDVInvokedUrlCommand*) command{
self.listenerCallbackId = command.callbackId;
CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK];
[pluginResult setKeepCallbackAsBool:true];
[self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
}
-(void)reportEvent:(NSDictionary*)eventData{
CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDictionary:eventData];
[pluginResult setKeepCallbackAsBool:true];
[self.commandDelegate sendPluginResult:pluginResult callbackId:self.listenerCallbackId];
}
这是插件的javascript部分:
var HybridBridge = (function() {
var PLUGIN_NAME = "HybridBridge";
var ACTION_BIND_LISTENER = "bindAction";
this.bindListener = function(listener) {
cordova.exec(listener, listener, PLUGIN_NAME, ACTION_BIND_LISTENER, []);
};
return this;
}());
这是javascript事件监听器:
var NativeEventsListener = (function() {
this.onReceivedEvent = function(eventData) {
var eventHandler = function(){};
switch (eventData.eventType){
case "colorButtonClicked":
eventHandler = colorButtonClickEvent;
break;
default:
}
eventHandler(eventData);
};
function colorButtonClickEvent(eventData){
changeBackgroundColor(eventData.color);
}
function changeBackground(color) {
document.body.style.background = color;
}
return this;
}());
这是将事件侦听器绑定到插件的 main.js 文件:
function wlCommonInit(){
HybridBridge.bindListener(NativeEventsListener.onReceivedEvent);
}
function wlEnvInit(){
wlCommonInit();
}
最后是objective-C中的插件调用:
- (IBAction)changeWebPageColor {
redColor = !redColor;
NSString *color = redColor ? @"red" : @"white";
HybridBridge *bridge = [self.pluginObjects objectForKey:@"HybridBridge"];
NSDictionary *eventData = [NSDictionary dictionaryWithObjectsAndKeys:
@"colorButtonClicked", @"eventType",
color, @"color",
nil];
[bridge reportEvent:eventData];
}
谢谢您的帮助!