iOS WKWebView的使用

给HTML添加JS代码

NSString *js = @"function xx() {return '我是事先注入的JS代码';}";
//初始化WKUserScript对象
//WKUserScriptInjectionTimeAtDocumentEnd为网页加载完成时注入
WKUserScript *script = [[WKUserScript alloc] initWithSource:js injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:YES];
//根据生成的WKUserScript对象,初始化WKWebViewConfiguration
WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];
[config.userContentController addUserScript:script];
    
self.webView = [[WKWebView alloc] initWithFrame:self.view.bounds configuration:config];
[self.view addSubview:self.webView];

NSString *filePath = [[NSBundle mainBundle] pathForResource:@"htmlTest" ofType:@"html"];
NSURL *url = [NSURL fileURLWithPath:filePath];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[self.webView loadRequest:request];

self.webView.UIDelegate = self;
self.webView.navigationDelegate = self;
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation
{
    NSString *jsFun = [NSString stringWithFormat:@"xx()"];
    [self.webView evaluateJavaScript:jsFun completionHandler:^(id _Nullable obj, NSError * _Nullable error) {
        NSLog(@"%@---%@",error,obj);
    }];
}

进度监听

self.webView = [[WKWebView alloc] initWithFrame:self.view.bounds];
[self.view addSubview:self.webView];
    
NSString *filePath = [[NSBundle mainBundle] pathForResource:@"htmlTest" ofType:@"html"];
NSURL *url = [NSURL fileURLWithPath:filePath];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[self.webView loadRequest:request];

[self.webView addObserver:self forKeyPath:@"estimatedProgress" options:(NSKeyValueObservingOptionNew) context:nil];
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context
{
    NSLog(@"%@",change[@"new"]);
}

获取HTML标签值

<!DOCTYPE html>
<html style="height: 100%">
    <head>
        <meta charset="utf-8">
            <meta name="viewport" content="width=device-width,minimum-scale=1.0,maximum-scale=1.0,user-scalable=no">
    </head>
    <body style="height: 100%; margin: 0;">
        <div id="word" style="height: 100%">你好!</div>
        <script type="text/javascript">
        </script>
    </body>
</html>
self.webView = [[WKWebView alloc] initWithFrame:self.view.bounds];
[self.view addSubview:self.webView];
    
NSString *filePath = [[NSBundle mainBundle] pathForResource:@"htmlTest" ofType:@"html"];
NSURL *url = [NSURL fileURLWithPath:filePath];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[self.webView loadRequest:request];
    
self.webView.UIDelegate = self;
self.webView.navigationDelegate = self;
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation
{
    NSString *jsFun = @"document.getElementById('word').innerHTML";
    [self.webView evaluateJavaScript:jsFun completionHandler:^(id _Nullable obj, NSError * _Nullable error) {
        NSLog(@"%@---%@",error,obj);
    }];
}

左滑返回

431BE1C7-A47D-4C6A-9069-007B4211B6A9.png

OC调用JS方法传参/返回值

传递单个字符串:

注意要加单引号,返回值在block回调里面

NSString *jsFun = [NSString stringWithFormat:@"getJsCode('%@')",@"你好!”];
[self.webView evaluateJavaScript:jsFun completionHandler:^(id _Nullable obj, NSError * _Nullable error) {
        NSLog(@"%@---%@",error,obj);
}];

传递json

NSDictionary *dict = @{
                           @"name": @"张三",
                           @"age": @(18)
                           };
NSData *data = [NSJSONSerialization dataWithJSONObject:dict
                                                   options:(NSJSONWritingPrettyPrinted)
                                                     error:nil];
NSString *str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
                     
NSString *jsFun = [NSString stringWithFormat:@"getJsCode(%@)",str];
[self.webView evaluateJavaScript:jsFun completionHandler:^(id _Nullable obj, NSError * _Nullable error) {
    NSLog(@"%@---%@",error,obj);
}];
<!DOCTYPE html>
<html style="height: 100%">
    <head>
        <meta charset="utf-8">
            <meta name="viewport"content="width=device-width,minimum-scale=1.0,maximum-scale=1.0,user-scalable=no">
    </head>
    <body style="height: 100%; margin: 0;">
        <div id="word"style="height: 100%">你好!</div>
        <script type="text/javascript">
            window.getJsCode = function(obj) {
                return'都啥科大数据库领导  '+ [obj.name](http://obj.name/)+ '  '+ obj.age;
            };
        </script>
    </body>
</html>

JS调用OC方法传参/返回值

WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];
self.webView = [[WKWebView alloc] initWithFrame:self.view.bounds configuration:config];
[self.view addSubview:self.webView];
    
NSString *filePath = [[NSBundle mainBundle] pathForResource:@"htmlTest" ofType:@"html"];
NSURL *url = [NSURL fileURLWithPath:filePath];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[self.webView loadRequest:request];
    
self.webView.UIDelegate = self;
self.webView.navigationDelegate = self;
[config.userContentController addScriptMessageHandler:self name:@"jsToOC"];
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message
{
    if ([message.name isEqualToString:@"jsToOC"]) {
        NSLog(@"---%@",message.body);
    }
}
<!DOCTYPE html>
<html style="height: 100%">
    <head>
        <meta charset="utf-8">
            <meta name="viewport" content="width=device-width,minimum-scale=1.0,maximum-scale=1.0,user-scalable=no">
    </head>
    <body style="height: 100%; margin: 0;">
        <div id="word" style="height: 100%">你好!</div>
        <script type="text/javascript">
            window.getJsCode = function (obj) {
                var a = {
                    'name': '张三',
                    'age': '22'
                };
                window.webkit.messageHandlers.jsToOC.postMessage(a);
            };
        </script>
    </body>
</html>
B9134D0B-99EF-4E7B-8099-9ADA1556726D.png
03246DE9-EECD-4702-9E71-1ABAE37CE6C8.png

推荐阅读更多精彩内容