美文网首页
WKWebView js调用OC OC调用js.-2022-03

WKWebView js调用OC OC调用js.-2022-03

作者: AqualCrystal | 来源:发表于2022-03-02 21:29 被阅读0次

1.js调用OC WKScriptMessageHandler协议 js注入

config.userContentController = wkUController;
注意:遵守WKScriptMessageHandler协议,代理是由WKUserContentControl设置
 //这个类主要用来做native与JavaScript的交互管理
 WKUserContentController * wkUController = [[WKUserContentController alloc] init];
//注册一个name为jsToOcNoPrams的js方法,设置处理接收JS方法的代理
 [wkUController addScriptMessageHandler:self  name:@"jsToOcNoPrams"];
 [wkUController addScriptMessageHandler:self  name:@"jsToOcWithPrams"];
config.userContentController = wkUController;
//用完记得移除
 //移除注册的js方法
[[_webView configuration].userContentController removeScriptMessageHandlerForName:@"jsToOcNoPrams"];
[[_webView configuration].userContentController removeScriptMessageHandlerForName:@"jsToOcWithPrams"];
//通过接收JS传出消息的name进行捕捉的回调方法
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message{
NSLog(@"name:%@\\\\n body:%@\\\\n frameInfo:%@\\\\n",message.name,message.body,message.frameInfo);
 //用message.body获得JS传出的参数体
NSDictionary * parameter = message.body;
//JS调用OC
 if([message.name isEqualToString:@"jsToOcNoPrams"]){
UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"js调用到了oc" message:@"不带参数" preferredStyle:UIAlertControllerStyleAlert];
 [alertController addAction:([UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
 }])];

  [self presentViewController:alertController animated:YES completion:nil];
}else if([message.name isEqualToString:@"jsToOcWithPrams"]){
UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"js调用到了oc" message:parameter[@"params"] preferredStyle:UIAlertControllerStyleAlert];
 [alertController addAction:([UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
}])];
[self presentViewController:alertController animated:YES completion:nil];
    }
}

2.JS调用OC方法。WKNavigationDelegate协议拦截
pragma mark - WKNavigationDelegate

- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler {
if ([navigationAction.request.URL.scheme caseInsensitiveCompare:@"jsToOc"] == NSOrderedSame) {
[WKWebViewInterceptController showAlertWithTitle:navigationAction.request.URL.host message:navigationAction.request.URL.query cancelHandler:nil];
decisionHandler(WKNavigationActionPolicyCancel);  
  }
    else {
        decisionHandler(WKNavigationActionPolicyAllow);
    }
}

3.js调用OC的弹出框, WKUIDelegate协议
//web界面中有弹出警告框时调用

- (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler
{
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"" message:message preferredStyle:UIAlertControllerStyleAlert];
    // 确定按钮
    UIAlertAction *alertAction = [UIAlertAction actionWithTitle:”” style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        completionHandler();
    }];
    [alertController addAction:alertAction];
    if (self.visibleNavigator) {
        [self.visibleNavigator presentViewController:alertController animated:YES completion:nil];
    }else{
        completionHandler();
    }
}

#pragma mark - WKUIDelegate
//! alert(message)
- (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler {

    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"Alert" message:message preferredStyle:UIAlertControllerStyleAlert];

    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {

        completionHandler();

    }];

    [alertController addAction:cancelAction];

    [self presentViewController:alertController animated:YES completion:nil];

}

//! confirm(message)

- (void)webView:(WKWebView *)webView runJavaScriptConfirmPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(BOOL))completionHandler {

    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"Confirm" message:message preferredStyle:UIAlertControllerStyleAlert];

    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {

        completionHandler(NO);    }];

    UIAlertAction *confirmAction = [UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {

        completionHandler(YES);    }];

    [alertController addAction:cancelAction];

    [alertController addAction:confirmAction];

    [self presentViewController:alertController animated:YES completion:nil];

}

//! prompt(prompt, defaultText)

- (void)webView:(WKWebView *)webView runJavaScriptTextInputPanelWithPrompt:(NSString *)prompt defaultText:(NSString *)defaultText initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(NSString *))completionHandler {

    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:prompt message:nil preferredStyle:UIAlertControllerStyleAlert];

    [alertController addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {

        textField.placeholder = defaultText;

    }];

    UIAlertAction *confirmAction = [UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {

        completionHandler(alertController.textFields[0].text);

    }];

    [alertController addAction:confirmAction];

    [self presentViewController:alertController animated:YES completion:nil];

}

2.OC调用js注入方法。 WKUserScript

以下代码适配文本大小,由UIWebView换为WKWebView后,会发现字体小了很多,这应该是WKWebView与html的兼容问题,解决办法是修改原网页,要么我们手动注入JS
        NSString *jSString = @"var meta = document.createElement('meta'); meta.setAttribute('name', 'viewport'); meta.setAttribute('content', 'width=device-width'); document.getElementsByTagName('head')[0].appendChild(meta);";

        //用于进行JavaScript注入

        WKUserScript *wkUScript = [[WKUserScript alloc] initWithSource:jSString injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:YES];

        [config.userContentController addUserScript:wkUScript];

        [self.webView evaluateJavaScript:@"ocToJs('loginSucceed', 'oc_tokenString')" completionHandler:^(id response, NSError *error) {}];

2.1.OC调用js注入方法 evaluateJavaScript:completionHandler

- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation {

    [webView evaluateJavaScript:@"document.title" completionHandler:^(NSString *title, NSError *error) {

        self.title = title;

    }];

}

https://www.jianshu.com/p/5cf0d241ae12/

https://www.jianshu.com/p/e23aa25d7514

https://www.jianshu.com/p/7a1fceae5880

相关文章

网友评论

      本文标题:WKWebView js调用OC OC调用js.-2022-03

      本文链接:https://www.haomeiwen.com/subject/mziurrtx.html