欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

IOS中UIWebView、WKWebView之JS交互

程序员文章站 2023-12-19 18:29:22
做客户端开发,肯定避免不了js交互,于是自己对苹果接口做了个简易封装: jsexport-->uiwebview+interaction、wkscriptmes...

做客户端开发,肯定避免不了js交互,于是自己对苹果接口做了个简易封装:

jsexport-->uiwebview+interaction、wkscriptmessagehandler -->wkwebview+interaction以备以后使用。

代码非常简洁,见这里:https://github.com/v5zhou/jsinteraction.git

旧方式

旧的交互方式有通过uiwebviewdelegate实现的:js与客户端定义好跳转页面参数,在将要跳转时捕获关键字,然后处理业务。

ios端:

- (bool)webview:(uiwebview *)webview shouldstartloadwithrequest:(nsurlrequest *)request navigationtype:(uiwebviewnavigationtype)navigationtype {
  nsstring *urlstring = [[request url] absolutestring];
  if ([urlstring isequaltostring:@"objc://loading"]) {
    if (_gotorootviewcontroller) {
      _gotorootviewcontroller();
    }
  }
  return yes;
}

js端:

<!doctype html>
<html>
  <title>test</title>
  <meta charset="utf-8">
    <body>
      <a href="javascript:document.location = 'objc://loading'" rel="external nofollow" class="btn">这是交互按钮</a>
    </body>
</html>

uiwebview+jsexport方式

导入javascriptcore.framework,并导入我的扩展类#import "uiwebview+interaction.h"。

使用方式

oc调js:

[_webview interactiontojs:@"alertmobile('15625298071')"];

js调oc:

- (void)webviewdidfinishload:(uiwebview *)webview {
  [self.webview interactiontooc:^(interactionoctype functiontype, nsdictionary *param) {
    switch (functiontype) {
      case interactionoctype_alert:
      {
        uialertview *alert = [[uialertview alloc] initwithtitle:param[@"title"] message:param[@"content"] delegate:nil cancelbuttontitle:nil otherbuttontitles:@"确定", nil];
        [alert show];
      }
        break;
      case interactionoctype_present:
      {
        self.modaltransitionstyle = uimodaltransitionstylecrossdissolve;
        class cls = nsclassfromstring(param[@"tocontroller"]);
        bool isanimate = [param[@"animate"] boolvalue];
        uiviewcontroller *ctl = [[cls alloc] init];
        [self presentviewcontroller:ctl animated:isanimate completion:nil];
      }
        break;

      default:
        break;
    }
  }];
}

添加动作

//自定义添加功能类型
typedef ns_enum(nsuinteger, interactionoctype) {
  interactionoctype_alert = 0,
  interactionoctype_present,
  interactionoctype_xxxxxxx,   //有啥需求就和这里添加
};

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

function mypresent(ctl) {
      var param = new array();
      param["animate"] = 1;
      param["tocontroller"] = "secondviewcontroller";
      webviewinteraction.callback(1, param);
    }

其中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);
    }
  });
}

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

上一篇:

下一篇: