WKWebView与js交互

最近项目中需要用到js与原生app交互, 点击h5中的按钮, 并把h5中的参数传递到原生页面.

1. 首先在app端遵守协议<WKScriptMessageHandler,WKNavigationDelegate,WKUIDelegate>

 

 

  WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];
  // 设置偏好设置
  config.preferences = [[WKPreferences alloc] init];
  config.preferences.minimumFontSize = 10;
  config.preferences.javaScriptEnabled = YES;
  config.preferences.javaScriptCanOpenWindowsAutomatically = NO;

  config.processPool = [[WKProcessPool alloc] init];

  // 通过JS与webview内容交互
  config.userContentController = [[WKUserContentController alloc] init];
  // 注入JS对象名称AppModel,当JS通过AppModel来调用时,
  // 我们可以在WKScriptMessageHandler代理中接收到
  [config.userContentController addScriptMessageHandler:self name:@"AppModel"];

        //通过默认的构造器来创建对象
  self.webView = [[WKWebView alloc] initWithFrame:self.view.bounds
                                    configuration:config];
  NSURL *path = [[NSBundle mainBundle] URLForResource:@"test" withExtension:@"html"];
  [self.webView loadRequest:[NSURLRequest requestWithURL:path]];
  [self.view addSubview:self.webView];

 

 

 

 

 

 

WKScriptMessageHandler代理回调

 

 

- (void)userContentController:(WKUserContentController *)userContentController
      didReceiveScriptMessage:(WKScriptMessage *)message {
  if ([message.name isEqualToString:@"AppModel"]) {
    // 打印所传过来的参数,只支持NSNumber, NSString, NSDate, NSArray,

    NSLog(@"%@", message.body);
       
  }
}


3. 在js中注入AppModel

 

 

 function buttonClick() {
      
      // AppModel是我们所注入的对象
      window.webkit.messageHandlers.AppModel.postMessage({body: '我是传递的参数'});
    }

 

 

 

=========== 分割线 ============

OC向js中传值

native调用js

OC端

 

// OC端
- (void)btnClick:(UIButton *)sender {
    [self.wkWebView evaluateJavaScript:@"jsFunc('张飞')" completionHandler:^(id _Nullable response, NSError * _Nullable error) {
        //TODO
        NSLog(@"%@ %@",response,error);
    }];
}


js端写

function jsFunc(name) {
    // 打印name参数
    // 点击OC中的按钮, js端该方法即可响应
    //TODO
}

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值