UIWebView中Objective-C和JavaScript

2017-12-09  本文已影响40人  aron1992

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的事件回调,主要步骤

  1. 定义JSContext的对象jsContext
  2. 在WebView的代理方法webViewDidFinishLoad:中调用[webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"]获取到JSContext的对象。
  3. 调用_jsContext[@"wst"] = self;注册JS中的对象wst派发的方法的处理模块,这里是把处理wst模块的代理设置为当前类,实际中如果有多个模块可以使用一个自定义的实现JSExport来单独处理JS的逻辑,本例中有实现了JSExport协议的自定义协议JavaScriptObjectiveCDelegate,具体看第4点
  4. 自定义继承JSExport协议JavaScriptObjectiveCDelegate,这边定义JS和OC交互的接口。
  5. 实现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");
    });
}
上一篇下一篇

猜你喜欢

热点阅读