iOS 与 js 交互

来源:互联网 发布:淘宝上下架查询 编辑:程序博客网 时间:2024/05/21 06:44


</pre><p>webView 上面的点击事件</p><p></p><p style="margin-top:0px; margin-bottom:0px; padding-top:0px; padding-bottom:0px; font-family:Arial; font-size:14px; line-height:26px">目前很流行的库有WebviewJavaScriptBridge和OVGap,这两个库都是让webview与JS建立起一条桥梁,</p><p style="margin-top:0px; margin-bottom:0px; padding-top:0px; padding-bottom:0px; font-family:Arial; font-size:14px; line-height:26px">这样就可以相互通信了。</p><p style="margin-top:0px; margin-bottom:0px; padding-top:0px; padding-bottom:0px; font-family:Arial; font-size:14px; line-height:26px">我目前只使用过WebviewJavaScriptBridge 这个类库,就拿这个来讲</p><p style="margin-top:0px; margin-bottom:0px; padding-top:0px; padding-bottom:0px; font-family:Arial; font-size:14px; line-height:26px">这个block 是用来接收点击接收到的参数data并赋值给_bridge</p><p style="margin-top:0px; margin-bottom:0px; padding-top:0px; padding-bottom:0px; font-family:Arial; font-size:14px; line-height:26px"></p><p class="p1"><span class="s1"></span></p><pre name="code" class="objc"> _bridge = [WebViewJavascriptBridge bridgeForWebView:_webView webViewDelegate:self handler:^(id data, WVJBResponseCallback responseCallback) {        WWLOG(@"ObjC received message from JS:%@",data);        responseCallback(@"Response for message from ObjC");    }];


这个是发送消息到js

[_bridgesend:@"A string sent from ObjC to JS"responseCallback:^(id response) {        WWLOG(@"sendMessage got response: %@", response);    }];


这个是带参数的

[_bridgecallHandler:@"testJavascriptHandler"data:data responseCallback:^(id response) {        WWLOG(@"testJavascriptHandler responded: %@", response);    }];


上gihut上面下载一个demo的很清楚的了

--------------------------------------------------------------------

iOS7 后出了了库 JavaScriptCore.frmeworks

#import <JavaScriptCore/JavaScriptCore.h>

这个库更容易使js根oc交互

在webView  - (void) webViewDidFinishLoad:(UIWebView *)webView 之后

调用

JSContext *context=[webViewvalueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];//获取js环境    NSString *alertJS=@"alert(‘呵呵’)";//准备执行的js代码    JSValue *result = [contextevaluateScript:alertJS];//通过oc方法调用js的alert  //有返回值的话会返回到result里面



对于webView上面的js点击事件

同样要Finishload之后 才能取到环境

JSContext *context=[webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];//获取js环境JSContext *context=[_webViewvalueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];    context[@"onclick"] = ^() {//点击调用  onclick是js点击调用的函数名  其实就是吧在js里面的函数调来在oc里面实现     就是oc里面的block实现对应js里面的函数体                NSArray *args = [JSContextcurrentArguments];//args里面装的是onClick(...)里面的参数列表,不是按顺序排列                for (JSValue *jsValin args) {            NSLog(@"%@", jsVal);        }                JSValue *this = [JSContextcurrentThis];        NSLog(@"%@",this);        NSLog(@"-------End Log-------");            };





0 0