美文网首页
WKWebView WKScriptMessageHandler

WKWebView WKScriptMessageHandler

作者: 一个默默无闻的程序猿 | 来源:发表于2020-05-08 13:02 被阅读0次

    OC代码

    - (WKWebView *)webView
    {
        if (!_webView) {
            WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];
            WKUserContentController * wkUController = [[WKUserContentController alloc] init];
            [wkUController addScriptMessageHandler:self name:@"jsCallOCFunction"];
            config.userContentController = wkUController;
            _webView = [[WKWebView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight - kNavHeight - kTabbarHeight)configuration:config];
            _webView.backgroundColor = [UIColor whiteColor];
            _webView.UIDelegate = self;
            _webView.scrollView.bounces = NO;
            _webView.navigationDelegate = self;
        }
        return _webView;
    }
    

    实现代理:这里以点击H5文件链接下载文件为例

    #pragma mark - WKScriptMessageHandler
    - (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message {
        NSDictionary *dic = message.body;
        if ([dic[@"method"] isEqualToString:@"downloadFilePreview"]) {
            NSString *url = dic[@"url"];
            NSMutableDictionary *params = [NSMutableDictionary dictionary];
            params[@"name"] = dic[@"name"];
            [MBProgressHUD showHUDAddedTo:self.view animated:YES];
            [HttpTool downLoadFileWithUrl:url params:params success:^(id json) {
                [MBProgressHUD hideHUDForView:self.view];
                if (json) {
                    DownLoadFilePreviewController *downVc = [[DownLoadFilePreviewController alloc]init];
                    downVc.url = json;
                    self.isrefresh = NO;
                    [self.navigationController pushViewController:downVc animated:YES];
                }else{
                    [MBProgressHUD hideHUDForView:self.view];
                    [MBProgressHUD showError:@"下载文件失败,请稍后重试"];
                }
            } failure:^(NSError *error) {
                [MBProgressHUD hideHUDForView:self.view];
                [MBProgressHUD showError:@"下载文件失败,请稍后重试"];
            }];
        }
    }
    

    H5代码

    window.webkit.messageHandlers.scan.postMessage() 
    

    相关文章

      网友评论

          本文标题:WKWebView WKScriptMessageHandler

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