UIWebView中Objective C和JavaScript通信

JS和OC的交互,使用到JavaScriptCore这个框架,用到的类和协议有JSExportJSContext

网页很简单,只有一个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");
    });
}
复制代码

转载于:https://juejin.im/post/5ca5d48ef265da309d08a3a2

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值