WKWebView与Javascript的交互

2017-03-20  本文已影响383人  李昭宏

最近在帮公司做新版本的时候,在加载一个H5界面的时候,需要和Javascript交互,之前只是会粗略使用WKWebView,今天就认真地上网查阅了一下资料


iOS App与JavaScript交互的流程

前言

With iOS 8 Apple has added a ton of user-facing goodness. The Health app, Apple Pay, and expanded TouchID capabilities — just a few things everyday users will be happy about. On the sdk side they’ve added a lot of cool things as well, but one I’m excited about is the addition of WKWebView. This is very similar to the related–but less powerful–UIWebView available since iOS 2. UIWebView offers simple methods for loading a remote url, navigating forwards and back, and even running basic JavaScript. In contrast WKWebView offers a full-blown configuration (via WKWebViewConfiguration), navigation (via WKNavigationDelegate), estimated loading progress, and evaluating JavaScript.
译文:相比于iOS2版本推出的UIWebView,iOS8推出的WKWebView提供了一系列的配置方案(WKWebViewConfiguration/WKNavigationDelegate),预估加载的进度和JavaScript的交互

At a high level passing information from native code to the JavaScript runtime is done by calling the evaluateJavaScript method on a WKWebView object. You can pass a block to capture errors but I’m not exploring that here. Passing information from JavaScript land to the iOS application uses the overly verbose Objective-C-style window.webkit.messageHandlers.NAME.postMessage function where NAME is whatever you call the script handler.
译文:通过调用WKWebView的evaluateJavaScript方法来实现传递信息,达到原生代码和JavaScript通讯的效果,你可以通过一个block来捕获错误,但是我并不会去关注那个部分,当你调用script handler(处理script操作)你要写window.webkit.messageHandlers这类冗长的充满警告的语句来实现JavaScript发送信息到iOS的应用

如何创建对象

创建WKWebView对象的交互
WKWebView instance (called webView)
WKWebViewConfiguration instance (called configuration)
WKUserContentController instance (called controller)
The constructor for WKWebView takes a configuration parameter. This allows an instance of WKWebViewConfiguration to be passed and additional settings configured. The important property is userContentController, an instance of WKUserContentController. This controller has a method called addScriptMessageHandler which is how messages from JavaScript land are sent to the native application. This is a big chunk of boilerplate that needs to get setup before the WKWebView can be loaded. Thankfully it’s not all bad.
Oh right, the ViewController needs to match the protocol defined by WKScriptMessageHandler. This means implementing the userContentController delegate method. Onwards to the code examples.
译文:WKWebView的初始化需要传入一个WKWebViewConfiguration参数,因此你需要初始化WKWebViewConfiguration的对象来设置配置。比较重要的就是userContentController这个属性,通过调用userContentController的addScriptMessageHandler方法来监听JavaScript的调用,这一步在初始化WKWebView之后就要加上监听 此外对应的控制器需要implement一个协议(WKScriptMessageHandler),然后在WKScriptMessageHandler这个delegate的回调中处理

实例代码

//ViewController.h
#import <WebKit/WebKit.h>
#import <UIKit/UIKit.h>

@interface ViewController : UIViewController <WKScriptMessageHandler>

@end
@interface ViewController ()

@property (nonatomic, strong) WKWebView *webView;

@end

#pragma mark - private method

//配置子控件
- (void)configView {
    [self.view addSubview:self.webView];
}

#pragma mark - WKScriptMessageHandler


- (void)userContentController:(WKUserContentController *)userContentController
      didReceiveScriptMessage:(WKScriptMessage *)message {
    
    // Log out the message received
    NSLog(@"Received event %@", message.body);
    
    // Then pull something from the device using the message body
    NSString *version = [[UIDevice currentDevice] valueForKey:message.body];
    
    // Execute some JavaScript using the result
    NSString *exec_template = @"set_headline(\"received: %@\");";
    NSString *exec = [NSString stringWithFormat:exec_template, version];
    [_webView evaluateJavaScript:exec completionHandler:nil];
}

#pragma mark - getter

- (WKWebView *)webView {
    if(_webView) {
        return _webView;
    }
    
    WKWebViewConfiguration *configuration = [[WKWebViewConfiguration alloc] init];
    
    WKUserContentController *controller = [[WKUserContentController alloc] init];
    configuration.userContentController = controller;
   [controller addScriptMessageHandler:self name:@"observe"];
    
    _webView = [[WKWebView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT-64) configuration:configuration];
    _webView.navigationDelegate = self;
    _webView.UIDelegate = self;
    
    return _webView;
}

另一种实例代码(网上的demo)

<html>
    <!--描述网页信息-->
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <title>小黄</title>
        <style>
            *{
                font-size: 50px;
            }
        
            .btn{height:80px; width:80%; padding: 0px 30px; background-color: #0071E7; border: solid 1px #0071E7; border-radius:5px; font-size: 1em; color: white}
        </style>
        
        <script>
            function clear() {
                document.getElementById('mobile').innerHTML = ''
                document.getElementById('name').innerHTML = ''
                document.getElementById('msg').innerHTML = ''
            }
        
            //OC调用JS的方法列表
            function alertMobile() {
                //这里已经调用过来了 但是搞不明白为什么alert方法没有响应
                //alert('我是上面的小黄 手机号是:13300001111')
                document.getElementById('mobile').innerHTML = '我是上面的小黄 手机号是:13300001111'
            }

            function alertName(msg) {
                //alert('你好 ' + msg + ', 我也很高兴见到你')
                document.getElementById('name').innerHTML = '你好 ' + msg + ', 我也很高兴见到你'
            }

            function alertSendMsg(num,msg) {
                //window.alert('这是我的手机号:' + num + ',' + msg + '!!')
                document.getElementById('msg').innerHTML = '这是我的手机号:' + num + ',' + msg + '!!'
            }
        
            //JS响应方法列表
            function btnClick1() {
                window.webkit.messageHandlers.showMobile.postMessage(null)
            }

            function btnClick2() {
                window.webkit.messageHandlers.showName.postMessage('xiao黄')
            }

            function btnClick3() {
                window.webkit.messageHandlers.showSendMsg.postMessage(['13300001111', 'Go Climbing This Weekend !!!'])
            }

        </script>
        
        
    </head>

    <!--网页具体内容-->
    <body>
        <br/>
        <div>
            <label>小黄:13300001111</label>
        </div>
        <br/>
        <div id="mobile"></div>
        <div>
            <button class="btn" type="button" onclick="btnClick1()">小红的手机号</button>
        </div>
        <br/>
        <div id="name"></div>
        <div>
            <button class="btn" type="button" onclick="btnClick2()">打电话给小红</button>
        </div>
        <br/>
        <div id="msg"></div>
        <div>
            <button class="btn" type="button" onclick="btnClick3()">发短信给小红</button>
        </div>
    </body>
</html>
//
//  ViewController.m
//  OC与JS交互之WKWebView
//
//  Created by user on 16/8/18.
//  Copyright © 2016年 rrcc. All rights reserved.
//

#import "ViewController.h"
#import <WebKit/WebKit.h>

@interface ViewController () <WKScriptMessageHandler>

@property (nonatomic, strong) WKWebView *wkWebView;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    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];
    
    WKUserContentController *userCC = config.userContentController;
    //JS调用OC 添加处理脚本
    [userCC addScriptMessageHandler:self name:@"showMobile"];
    [userCC addScriptMessageHandler:self name:@"showName"];
    [userCC addScriptMessageHandler:self name:@"showSendMsg"];
}

//网页加载完成之后调用JS代码才会执行,因为这个时候html页面已经注入到webView中并且可以响应到对应方法
- (IBAction)buttonClick:(UIButton *)sender {
    if (!self.wkWebView.loading) {
        if (sender.tag == 123) {
            [self.wkWebView evaluateJavaScript:@"alertMobile()" completionHandler:^(id _Nullable response, NSError * _Nullable error) {
                //TODO
                NSLog(@"%@ %@",response,error);
            }];
        }
        
        if (sender.tag == 234) {
            [self.wkWebView evaluateJavaScript:@"alertName('小红')" completionHandler:nil];
        }
        
        if (sender.tag == 345) {
            [self.wkWebView evaluateJavaScript:@"alertSendMsg('18870707070','周末爬山真是件愉快的事情')" completionHandler:nil];
        }

    } else {
        NSLog(@"the view is currently loading content");
    }
}

#pragma mark - WKScriptMessageHandler

- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message {
    NSLog(@"%@",NSStringFromSelector(_cmd));
    NSLog(@"%@",message.body);

    if ([message.name isEqualToString:@"showMobile"]) {
        [self showMessage:@"我是下面的小红 手机号是:18870707070"];
    }
    
    if ([message.name isEqualToString:@"showName"]) {
        NSString *info = [NSString stringWithFormat:@"你好 %@, 很高兴见到你",message.body];
        [self showMessage:info];
    }
    
    if ([message.name isEqualToString:@"showSendMsg"]) {
        NSArray *array = message.body;
        NSString *info = [NSString stringWithFormat:@"这是我的手机号: %@, %@ !!",array.firstObject,array.lastObject];
        [self showMessage:info];
    }
}

- (void)showMessage:(NSString *)message {
    [[[UIAlertView alloc] initWithTitle:nil message:message delegate:nil cancelButtonTitle:nil otherButtonTitles:@"OK", nil] show];
}

- (IBAction)clear:(id)sender {
    [self.wkWebView evaluateJavaScript:@"clear()" completionHandler:nil];
}

@end

总结

Objective-C 调用JavaScript 
使用方法:evaluateJavaScript: completionHandler:
JavaScript 调用 Objective-C,app端接收回调
回调方法:(void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message;
app端监听使用 addScriptMessageHandler:
上一篇下一篇

猜你喜欢

热点阅读