cordova插件Javascript函数从iOS 4.0.0的Native调用
我正尝试从cordova iOS 4.0.0的本机插件中调用javascript函数。 在以前的cordova ios版本3.9.2中,我可以像这样从本地插件调用任何javascript函数。
- (void)PlayMp3:(CDVInvokedUrlCommand*)command { NSString* callbackId = [command callbackId]; NSString* name = [[command arguments] objectAtIndex:0]; NSString* msg = [NSString stringWithFormat: @"Hello, %@", name]; CDVPluginResult* result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:msg]; MainViewController* viewController = (MainViewController*)self.viewController; NSString *jsCallBack = [NSString stringWithFormat:@"setPlayStatus();"]; [viewController.webView stringByEvaluatingJavaScriptFromString:jsCallBack]; [self success:result callbackId:callbackId]; }
但是在Cordova iOS 4.0.0中,我不能像上面那样调用javascript函数setPlayStatus()
。 因为viewController.webview
不是UIWebView
types。 这是UIView
。 所以我试图这样。
- (void)PlayMp3:(CDVInvokedUrlCommand*)command { CDVPluginResult* pluginResult = nil; NSString* echo = [command.arguments objectAtIndex:0]; if (echo != nil && [echo length] > 0) { pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:echo]; } else { pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR]; } WKWebView* webview = (WKWebView*)self.viewController.view; NSString *jsCallBack = [NSString stringWithFormat:@"setPlayStatus();"]; [webview evaluateJavaScript:@"setPlayStatus();" completionHandler:nil]; [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId]; }
但它没有工作。 如何在Cordova Plugin iOS 4.0.0的本机cordova插件中调用javascript函数?
谢谢大家。 我已经做了。 CDVPlugin
有一个commandDelegate
。 这个commandDelegate
可以用evalJS
函数调用javascript
函数。 所以我就这样试了
[self.commandDelegate evalJS:@"setPlayStatus()"];
之后, setPlayStatus()
函数被调用。
我只是快速阅读了Cordova iOS插件代码,它看起来像self.viewController.webView通过webEngine持有一个UIWebView。 它可能是可以的。
您应该使用isKindOfClass:
在投射之前检查。
编辑:甚至更好:引擎是这样的协议:
- (void)evaluateJavaScript:(NSString*)javaScriptString completionHandler:(void (^)(id, NSError*))completionHandler;
使用:
[self.viewController.webViewEngine evaluateJavaScript:@"setPlayStatus();" completionHandler:nil]
我试过自己,这对我有用
[self.webViewEngine evaluateJavaScript:[NSString stringWithFormat:@"funcName(%@)",yourparam]]
@Tim Rogers的答案中有一个错误,它应该是evalJs而不是evalJS:
[self.commandDelegate evalJs:@"setPlayStatus()"];
它适用于Cordova ios 4.1.1
对不起,我没有50个声望来添加评论,所以不得不在这里添加一个新的答案
我正面临同样的问题,我在下面的代码尝试从本地调用.js调用,并再次使用Cordova.exec发送参数
[self.webViewEngine evaluateJavaScript:[NSString stringWithFormat:@"setPlayStatus()"];
下面的function你必须在config.xml中添加
<feature name="setPlayStatus"> <param name="ios-package" value="setPlayStatus" /> <param name="onload" value="true" /> </feature>
这对我有用。