IOS Webview JS交互之事件拦截获取

来源:互联网 发布:js设置字符串的编码 编辑:程序博客网 时间:2024/06/10 21:13

   最近项目中用到了webvVew,webView加载的网页中有两个按钮,要在app里面响应这两个按钮的点击事件,并接受JS传过来的参数。

  ios7 的时候,出来了一个新的类库叫JavaScriptCore.framework

- (void)setupJsContent{    //获取当前JS环境    _content = [_webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];    // 打印异常    _content.exceptionHandler =    ^(JSContext *context, JSValue *exceptionValue)    {        context.exception = exceptionValue;        LogInfo(@"%@", exceptionValue);    };    //获取JS事件    WS(bself);    _content[@"showtag"] = ^(int num,NSString *tag){        LogInfo(@"num = %d   \n tag = %@",num,tag);        if (num == 1) {     //查看项目所在地            //获取经纬度            NSArray *locationArray = [tag componentsSeparatedByString:@","];            ProjectLocationViewController *locationCtrl = [[ProjectLocationViewController alloc]init];            locationCtrl.longitude = [locationArray[0] floatValue];            locationCtrl.latitude = [locationArray[1] floatValue];            [bself.navigationController pushViewController:locationCtrl animated:YES];        }else if(num == 2){            UIAlertView *alter = [[UIAlertView alloc]initWithTitle:@"标题" message:@"内容" delegate:nil cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];            alter.alertViewStyle = UIAlertViewStylePlainTextInput;                        [alter show];        }    };}

拦截JS中“showtag”事件,并接受参数,自定义响应事件
iOS webView JS交互还有一个第三方库 地址 :https://github.com/marcuswestin/WebViewJavascriptBridge  

0 0
原创粉丝点击