在webView中实现oc与js的交互一般有两种方式:
1、拦截点击事件的URL进行交互
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{
NSString *path=[[request URL] absoluteString];
if ([path isEqualToString:[NSString stringWithFormat:@"%@/ddhong/user/bindMadaiAccountSuc.jsp",kBaseUrl]]) {
....进行事件处理.......
}
if (navigationType == UIWebViewNavigationTypeLinkClicked)
{
NSString *path=[[request URL] absoluteString];
if ([path isEqualToString:[NSString stringWithFormat:@"%@/application/skiptoalllistcreditloan",kBaseUrl]]) {
.....进行事件处理......
}
}
return YES;
}
2、用JavaScriptCore实现交互
导入头文件:
#import<JavaScriptCore/JavaScriptCore.h
@protocol JSObjcDelegate <JSExport>
//这两个方法的名字必须与js页面里面调用的方法名字一致
- (void)jumpPublishDynamic;
- (void)jumpLogin;
@end
@interfaceViewController()
@property(nonatomic,strong)UIWebView*webView;
@property(nonatomic,strong)JSContext *jsContext;
@end
@implementation ViewController
- (void)viewDidLoad {
[superviewDidLoad];
[selfCustomUI];
}
- (void)CustomUI{
self.webView = [[UIWebViewalloc]initWithFrame:self.view.bounds];
self.webView.delegate =self;
[self.view addSubview:_webView];
NSURL*url = [[NSBundlemainBundle] URLForResource:@"untitled3"withExtension:@"html"];
[self.webView loadRequest:[NSURLRequestrequestWithURL:url]];
}
- (void)webViewDidFinishLoad:(UIWebView*)webView{
self.jsContext = [webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
//此处的JSInterface必须与js页面调用方面的类名名字一致
self.jsContext[@"JSInterface"] = self;
self.jsContext.exceptionHandler = ^(JSContext *context, JSValue *exceptionValue) {
context.exception = exceptionValue;
NSLog(@"异常信息:%@", exceptionValue);
};
}
//js调用oc方法的实现
#pragma mark - JSObjcDelegate
- (void)jumpPublishDynamic {
[self pushController:[PublishViewController class] withTitle:@""];
}
- (void)jumpLogin {
[self pushController:[LoginViewController class] withInfo:nil];
}