JS与OC的交互

JS与OC交互、js事件注入、修改js方法实现

2019-12-16  本文已影响0人  年轻就要活出样

序言

由于UIWebview即将废弃,相比较于WKWebview,通过测试即可发现UIWebview占用更多内存,且内存很夸张。WKWebView网页加载速度也有提升,但是并不像内存那样提升那么多。下面列举一些其它的优势:

一、JS与OC交互

#pragma mark --  初始化
- (void)initView{
       WKWebViewConfiguration *configuration = [[WKWebViewConfiguration alloc] init];
       WKPreferences *preference = [WKPreferences new];
       preference.javaScriptCanOpenWindowsAutomatically = YES;
       preference.minimumFontSize = 40.0;
       configuration.preferences = preference;
       
       // WKWebView
       CGRect webViewFrame = CGRectMake(0, 180, self.view.bounds.size.width, self.view.bounds.size.height * 0.8);
       self.webView = [[WKWebView alloc] initWithFrame:webViewFrame configuration:configuration];
       NSString *urlStr = [[NSBundle mainBundle] pathForResource:@"index.html" ofType:nil];
       NSURL *fileURL = [NSURL fileURLWithPath:urlStr];
       [self.webView loadFileURL:fileURL allowingReadAccessToURL:fileURL];
       
       self.webView.navigationDelegate = self;
       self.webView.UIDelegate = self;
       [self.view addSubview:self.webView];
       [self addJSActionByOC];
}
#pragma mark --  生命周期
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    // addScriptMessageHandler 很容易导致循环引用
    // 控制器 强引用了WKWebView,WKWebView copy(强引用了)configuration, configuration copy (强引用了)userContentController
    // userContentController 强引用了 self (控制器)
    // js调用oc方之前要进行注册
    [self.webView.configuration.userContentController addScriptMessageHandler:self name:@"Location"];
    [self.webView.configuration.userContentController addScriptMessageHandler:self name:@"Share"];
    [self.webView.configuration.userContentController addScriptMessageHandler:self name:@"Color"];
    [self.webView.configuration.userContentController addScriptMessageHandler:self name:@"GoBack"];
    [self.webView.configuration.userContentController addScriptMessageHandler:self name:@"ocZRAction"];
    [self.webView.configuration.userContentController addScriptMessageHandler:self name:@"asyncAction"];
}
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    
    // 因此这里要记得移除handlers
    [self.webView.configuration.userContentController removeScriptMessageHandlerForName:@"Location"];
    [self.webView.configuration.userContentController removeScriptMessageHandlerForName:@"Share"];
    [self.webView.configuration.userContentController removeScriptMessageHandlerForName:@"Color"];
    [self.webView.configuration.userContentController removeScriptMessageHandlerForName:@"GoBack"];
    [self.webView.configuration.userContentController removeScriptMessageHandlerForName:@"ocZRAction"];
    [self.webView.configuration.userContentController removeScriptMessageHandlerForName:@"asyncAction"];
}
        <input type="button" value="oc拦截alert提示" onclick="colorClick()" />
        function colorClick() {
                alert('55555')
            }
#pragma mark - WKUIDelegate
- (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler {
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提醒" message:message preferredStyle:UIAlertControllerStyleAlert];
    [alert addAction:[UIAlertAction actionWithTitle:@"知道了" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        completionHandler();
    }]];
    
    [self presentViewController:alert animated:YES completion:nil];
}

WKScriptMessageHandler是因为我们要处理JS调用OC方法的请求。
WKScriptMessage有两个关键属性name 和 body。
因为我们给每一个OC 方法取了一个name,那么我们就可以根据name 来区分执行不同的方法。body 中存着JS 要给OC 传的参数。

        <input type="button" value="调用oc方法传递事件" onclick="goBack()" />
        function goBack() {
                window.webkit.messageHandlers.asyncAction.postMessage("传递数据");
            }
#pragma mark - WKScriptMessageHandler

- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message {
    // message.body  --  Allowed types are NSNumber, NSString, NSDate, NSArray,NSDictionary, and NSNull.
    if ([message.name isEqualToString:@"Location"]) {

    } else if ([message.name isEqualToString:@"Share"]) {

    } else if ([message.name isEqualToString:@"Color"]) {

    }else if ([message.name isEqualToString:@"GoBack"]) {
        
    }else if ([message.name isEqualToString:@"asyncAction"]) {
        NSLog(@"假死页面回调事件");
    }else if ([message.name isEqualToString:@"ocZRAction"]){
        NSLog(@"oc注入方法,调用oc事件  message = %@",message.body);
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提醒" message:@"调用成功" preferredStyle:UIAlertControllerStyleAlert];
           [alert addAction:[UIAlertAction actionWithTitle:@"知道了" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {

           }]];
           
           [self presentViewController:alert animated:YES completion:nil];
    }
    
}

二、JS事件注入

ocAddAction方法在js文件中并没有定义

        <input type="button" value="oc注入js事件,调用oc" onclick="ocAddAction()" />

实现WKNavigationDelegate协议方法,执行之后会在WKScriptMessageHandler代理方法中拦截到ocZRAction

#pragma mark - WKNavigationDelegate
///加载完成网页的时候才开始注入JS代码,要不然还没加载完时就可以点击了,就不能调用我们的代码了!
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation{
    NSString *jsCode = @"function ocAddAction(a,b,c){\
        window.webkit.messageHandlers.ocZRAction.postMessage('js注入')\
    }";
    [self.webView evaluateJavaScript:jsCode completionHandler:^(id _Nullable obj, NSError * _Nullable error) {

    }];
}

三、动态修改JS系统函数或者自定义函数实现

动态修改alert系统函数的实现,当js中调用alert函数时,触发的是我们自定义方法

#pragma mark --  通过js注入,修改js内部函数或者系统函数内部实现
- (void)addJSActionByOC{
    NSString *jsCode = @"alert = (function (oriAlertFunc){ \
                          return function(task)\
                          {\
                           window.webkit.messageHandlers.ocZRAction.postMessage(task);\
                           oriAlertFunc.call(alert,task);\
                          }\
                          })(alert);";
         
    //injected the method when H5 starts to create the DOM tree
    [self.webView.configuration.userContentController addUserScript:[[WKUserScript alloc] initWithSource:jsCode injectionTime:WKUserScriptInjectionTimeAtDocumentStart forMainFrameOnly:YES]];
}
        <input type="button" value="获取定位" onclick="locationClick()" />
       function locationClick() {
                alert('4444')
            }

URL Scheme拦截的问题,这里不做赘述,请看demo
JS注入详情
参考链接:
链接一
链接二

上一篇 下一篇

猜你喜欢

热点阅读