iOS 在UIWebView中JavaScriptCore实现OC与JS的交互

在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];

}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 一、简介 近两年随着HTML5的迅速发展与日趋成熟,越来越多的移动开发者选择使用HTML5来进行混合开发,不仅节约...
    RainyGY阅读 1,909评论 1 12
  • 随着H5技术的兴起,在iOS开发过程中,难免会遇到原生应用需要和H5页面交互的问题。其中会涉及方法调用及参数传值等...
    Chris_js阅读 3,125评论 1 8
  • 项目开发中,会推一些活动供用户参加,活动页面一般都是用h5或者web页面,这活动页面有时候需要跟移动端有交互操作,...
    hnxyzhw阅读 714评论 0 4
  • 一、简介 近两年随着HTML5的迅速发展与日趋成熟,越来越多的移动开发者选择使用HTML5来进行混合开发,不...
    宝宝teacher阅读 2,372评论 3 15
  • 链接:http://ios.jobbole.com/89330/ 其实一直想给大家整理一下JS与OC的交互,但是没...
    Kean_Qi阅读 385评论 0 1