美文网首页
使用WKWebView与H5交互

使用WKWebView与H5交互

作者: JACK_岩 | 来源:发表于2018-11-26 14:26 被阅读12次

    1.注册代理
    <WKUIDelegate,WKNavigationDelegate,WKScriptMessageHandler>
    2.新建webview和实例化WKWebViewConfiguration对象

    _webView = [[WKWebView alloc] init];
    //初始化WKWebViewConfiguration
    WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];
    // 实例化对象
    config.userContentController = [WKUserContentController new];
    [config.userContentController addScriptMessageHandler:self name:@"returnMsg"];
    // 进行偏好设置
    WKPreferences *preferences = [WKPreferences new];
    preferences.javaScriptCanOpenWindowsAutomatically = YES;
    config.preferences = preferences;
    self.webView = [[WKWebView alloc] initWithFrame:CGRectMake(0, HuiStutasH, SCREEN_WIDTH, SCREEN_HEIGHT-HuiStutasH - (kDevice_Is_iPhoneX ? 34 : 0)) configuration:config];
    [self.view addSubview:_webView];
    //设置代理
    _webView.UIDelegate = self;
    _webView.navigationDelegate = self;
    [_webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:self.urlStr]]];
    

    3.代理方法
    //H5回调 TODO
    // 添加scriptMessageHandler

    • (void)addScriptMessageHandler:(id <WKScriptMessageHandler>)scriptMessageHandler name:(NSString *)name{}

    • (void)userContentController:(nonnull WKUserContentController *)userContentController didReceiveScriptMessage:(nonnull WKScriptMessage *)message {

      if ([message.name isEqualToString:@"returnMsg"]) {

        //跳转到借款记录
        TCRecordVC *recordVC = [[TCRecordVC alloc] init];
        recordVC.typeNum = @1;
        [self.navigationController pushViewController:recordVC animated:YES];
      

      }
      }

    4.H5代码
    window.webkit.messageHandlers.returnMsg.postMessage()

    相关文章

      网友评论

          本文标题:使用WKWebView与H5交互

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