JS调用OC方法
2015-08-14 17:19 dengchaojie_learner 阅读(1228) 评论(0) 收藏 举报JS调Native
http://www.cnblogs.com/dailc/p/5931322.html
引入官方的库文件
#import <JavaScriptCore/JavaScriptCore.h>
Native注册api函数(OC)
//webview加载完毕后设置一些js接口
-(void)webViewDidFinishLoad:(UIWebView *)webView{
[self hideProgress];
[self setJSInterface];
}
-(void)setJSInterface{
JSContext *context =[_wv valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
// 注册名为foo的api方法
context[@"foo"] = ^() {
//获取参数
NSArray *args = [JSContext currentArguments];
NSString *title = [NSString stringWithFormat:@"%@",[args objectAtIndex:0]];
//做一些自己的逻辑
//返回一个值 'foo:'+title
return [NSString stringWithFormat:@"foo:%@", title];
};
}
Html中JS调用原生的代码
//调用方法,用top是确保调用到最顶级,因为iframe要用top才能拿到顶级
window.top.foo('test'); //返回:'foo:test'
如上所示,Native中通过引入官方提供的JavaScriptCore库(iOS7中出现的),然后可以将api绑定到JSContext上(然后Html中JS默认通过window.top.***可调用)。有如下特点
- iOS7才出现这种方式,在这之前,js无法直接调用Native,只能通过JSBridge方式简介调用
- JS能调用到已经暴露的api,并且能得到相应返回值
- iOS原生本身是无法被JS调用的,但是通过引入官方提供的第三方"JavaScriptCore",即可开放api给JS调用
https://blog.csdn.net/u011619283/article/details/52700601
- (void)myMethod:(CDVInvokedUrlCommand*)command
{
NSString* echo = [command.arguments objectAtIndex:0];
NSLog(@"%@",echo);
POSJiaoyiViewController *sele=[[POSJiaoyiViewController alloc] init];
[self.viewController.navigationController pushViewController:sele animated:YES];
userDefaults=[NSUserDefaults standardUserDefaults];
if (echo != nil && [echo length] > 0) {
[self.commandDelegate runInBackground:^{
CDVPluginResult* pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:echo];
[self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
}];
} else {
[self.commandDelegate runInBackground:^{
CDVPluginResult* pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"Arg was null"];
[self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
}];
}
}
浙公网安备 33010602011771号