JS和OC的交互,使用到JavaScriptCore
这个框架,用到的类和协议有JSExport
、JSContext
网页很简单,只有一个button按钮,button按钮的事件点击主要执行了wst.duobao('123');
,wst
是自定义的一个普通JS对象,在OC中需要使用到wst
捕获对应的js方法调用。
网页html代码如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>html5page-oc</title>
<script>
wst = new Object();
wst.duobao = function () {}
function btn1Click() {
wst.duobao('123');
alert("after call");
}
</script>
</head>
<body>
<input type="button" value="button c" onclick="btn1Click()">
</body>
</html>
OC处理JS的事件回调,主要步骤
- 定义
JSContext
的对象jsContext
。 - 在WebView的代理方法
webViewDidFinishLoad:
中调用[webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"]
获取到JSContext
的对象。 - 调用
_jsContext[@"wst"] = self;
注册JS中的对象wst
派发的方法的处理模块,这里是把处理wst
模块的代理设置为当前类,实际中如果有多个模块可以使用一个自定义的实现JSExport
来单独处理JS的逻辑,本例中有实现了JSExport
协议的自定义协议JavaScriptObjectiveCDelegate
,具体看第4点
。 - 自定义继承
JSExport
协议JavaScriptObjectiveCDelegate
,这边定义JS和OC交互的接口。 - 实现JavaScriptObjectiveCDelegate,重写对应的方法处理JS的回调,注意JS回调的方法是在子线程执行的,如果涉及到UI操作,需要派发到主线程中处理。
OC调用JS方法
调用JSContext
的方法evaluateScript
,参数为JS代码即可
[_jsContext evaluateScript:@"alert('oc call js')"];
完整的代码如下:
// 自定义继承`JSExport`协议,这边定义JS和OC交互的接口
@protocol JavaScriptObjectiveCDelegate <JSExport>
- (void)duobao(NSString*)params;
@end
@interface YTTWebViewController ()<UIWebViewDelegate, UIScrollViewDelegate, JavaScriptObjectiveCDelegate>
@property (nonatomic, strong) UIWebView *webView;
@property (nonatomic, strong, readonly) JSContext *jsContext;
@end
// ...
- (void)webViewDidFinishLoad:(UIWebView *)webView
{
if (_jsContext == nil) {
// 1.从WebView中获取到JSContext对象
_jsContext = [webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
// 2. 关联打印异常
_jsContext.exceptionHandler = ^(JSContext *context, JSValue *exceptionValue) {
context.exception = exceptionValue;
NSLog(@"异常信息:%@", exceptionValue);
};
_jsContext[@"wst"] = self;
}
// OC调用JS
[_jsContext evaluateScript:@"alert('oc call js')"];
}
#pragma mark - JavaScriptObjectiveCDelegate
-(void)duobao {
// JS调用OC是在子线程
NSLog(@"current thread = %@", [NSThread currentThread]);
dispatch_async(dispatch_get_main_queue(), ^{
NSLog(@"js call oc");
});
}
网友评论