IOS中UIWebView、WKWebView之JS交互

2020-01-20 23:24:46王冬梅

其中callBack是通过这个JSExport实现的


@protocol WebViewJSExport <JSExport>
JSExportAs
(callBack /** callBack 作为js方法的别名 */,
 - (void)awakeOC:(InterActionOcType)type param:(NSDictionary *)param
 );
@end

WKWebView+WKScriptMessageHandler方式

导入WebKit.framework,并导入我的扩展类#import "WKWebView+Interaction.h"。

使用方式

OC调JS:


[self.wkWebView InterActionToJs:@"JSReloadTitle('你点了刷新JS按钮,我没猜错!')"];

JS调OC:


//注册交互类型
  [self.wkWebView registerScriptTypes:@{@"OCDismiss" : @(WKInterActionOcType_dismiss),
                     @"OCShowAlert" : @(WKInterActionOcType_alert)}];

  [self.wkWebView InterActionToOc:^(WKInterActionOcType functionType, NSDictionary *param) {
    switch (functionType) {
      case WKInterActionOcType_dismiss:
      {
        BOOL isAnimate = [param[@"animate"] boolValue];
        [self dismissViewControllerAnimated:isAnimate completion:nil];
      }
        break;
      case WKInterActionOcType_alert:
      {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"JS去做平方" message:nil delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
        alert.alertViewStyle = UIAlertViewStylePlainTextInput;
        [alert show];
      }
        break;
      default:
        break;
    }
  }];

添加动作


//自定义添加功能类型
typedef NS_ENUM(NSUInteger, WKInterActionOcType) {
  WKInterActionOcType_alert = 0,
  WKInterActionOcType_dismiss,
  WKInterActionOcType_xxxxxxx,   //有啥需求就和这里添加
};

并且对应的html中添加JS,参数封装为字典形式。例:


//js调oc
function myDismiss() {
  window.webkit.messageHandlers.OCDismiss.postMessage({"animate" : 1});  //这里的OCDismiss对应注册类型
}

其中callBack是通过WKScriptMessageHandler实现的


- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message {
  dispatch_async(dispatch_get_main_queue(), ^{
    NSString *name = message.name;
    NSDictionary *value = message.body;
    WKInterActionOcType type = [self.typeDict[name] integerValue];
    if (self.block) {
      self.block(type, value);
    }
  });
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持ASPKU。


注:相关教程知识阅读请移步到IOS开发频道。