WKWebView和JS交互使用

2017-02-24  本文已影响63人  我是三人禾

越来越多的项目中使用Native和网页的混合开发,这使得纯客户端工作大大减轻。随着手机硬件的提升,软件卡顿问题也会越来越小。之前做web端交互的时候,用的WebViewJavascriptBridge的库,这个库十分强大,只是oc端和web端定好function的名称,就可以互通消息,但本篇只记录WKWebView原生代码交互,如果有错误,还请指教。

    WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];
    config.preferences.minimumFontSize = 18;
    self.wkWebView = [[WKWebView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.height/2) configuration:config];
    [self.view addSubview:self.wkWebView];
    NSString *filePath = [[NSBundle mainBundle] pathForResource:@"index" ofType:@"html"];
    NSURL *baseURL = [[NSBundle mainBundle] bundleURL];
    [self.wkWebView loadHTMLString:[NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil] baseURL:baseURL];
    //  config.userContentController 点击去看到这属性是:  就是把前面这个和web视图联系起来
    WKUserContentController *userCC = config.userContentController;
    //JS调用OC 添加处理脚本
/*! @abstract Adds a script message handler.
 @param scriptMessageHandler The message handler to add.
 @param name The name of the message handler.
 @discussion Adding a scriptMessageHandler adds a function
 window.webkit.messageHandlers.<name>.postMessage(<messageBody>) for all
 frames.
 */
    [userCC addScriptMessageHandler:self name:@"showMobile_qin"];
    [userCC addScriptMessageHandler:self name:@"showName"];
    [userCC addScriptMessageHandler:self name:@"showSendMsg"];
#pragma mark - WKScriptMessageHandler

- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message {
    NSLog(@"userScripts:%@",userContentController.userScripts);
    NSLog(@"name:%@,,body:%@",message.name,message.body);
    if ([message.name isEqualToString:@"showSendMsg"]) {
        NSDictionary *dic = message.body;
        NSString *info = [NSString stringWithFormat:@"message是:%@",dic[@"message"]];
        NSLog(@"info:%@",info);
    }
}
这是html互通消息端固定的格式写法
 window.webkit.messageHandlers.<name>.postMessage(<messageBody>) for all
// JS代码  事件列表
        function btnClick() {
            var dic = {"message": "JS发消息给OC", "ls": "李四1" };
  window.webkit.messageHandlers.showSendMsg.postMessage(dic);
            }

    [self.wkWebView evaluateJavaScript:@"alertSendMsg('OC端','呼唤')" completionHandler:^(id _Nullable other, NSError * _Nullable error) {
                
                NSLog(@"other:%@,error:%@",other,error);
                
            }];
 <script>
    function alertSendMsg(num,msg) {
document.getElementById('demo').innerHTML = '已接收' + num + ',' + msg + '!!'
            }
</script>

OK,大概就是这样,这个demo中,没有多么负责的功能,但是js 和oc 互通消息已经能做到了。

demo地址

上一篇下一篇

猜你喜欢

热点阅读