WKWebView

OC--WKWebView的JS与OC交互、Cookie管理

2017-10-24  本文已影响365人  啊哈呵

完全抄录:iOS中UIWebView与WKWebView、JavaScript与OC交互、Cookie管理看我就够(中)
iOS UIWebView 和 WKWebView 的 cookie 获取,设置,删除

WKWebView

是Apple于iOS 8.0推出的WebKit中的核心控件,用来替UIWebView。
WKWebView比UIWebView的优势在于:

1、更多的支持HTML5的特性
2、高达60fps的滚动刷新率以及内置手势
3、与Safari相同的JavaScript引擎
4、将UIWebViewDelegate与UIWebView拆分成了14类与3个协议(官方文档说明
5、可以获取加载进度:estimatedProgress(UIWebView需要调用私有Api)

WKUserContentController

@property (nonatomic, strong) WKUserContentController *userContentController;
@interface WKUserContentController : NSObject <NSCoding>
//读取添加过的脚本
@property (nonatomic, readonly, copy) NSArray<WKUserScript *> *userScripts;
//添加脚本
- (void)addUserScript:(WKUserScript *)userScript;
//删除所有添加的脚本
- (void)removeAllUserScripts;
//通过window.webkit.messageHandlers.<name>.postMessage(<messageBody>) 来实现js->oc传递消息,并添加handler
- (void)addScriptMessageHandler:(id <WKScriptMessageHandler>)scriptMessageHandler name:(NSString *)name;
//删除handler
- (void)removeScriptMessageHandlerForName:(NSString *)name;
@end

创建一个WKWebView的代码如下:

WKWebViewConfiguration *configuration = [[WKWebViewConfiguration alloc] init];
WKUserContentController *controller = [[WKUserContentController alloc] init];
configuration.userContentController = controller;
self.webView = [[WKWebView alloc] initWithFrame:self.view.bounds configuration:configuration];
self.webView.allowsBackForwardNavigationGestures = YES; //允许右滑返回上个链接,左滑前进
self.webView.allowsLinkPreview = YES; //允许链接3D Touch
self.webView.customUserAgent = @"WebViewDemo/1.0.0"; //自定义UA,UIWebView就没有此功能,后面会讲到通过其他方式实现
self.webView.UIDelegate = self;
self.webView.navigationDelegate = self;
[self.view addSubview:self.webView];

一些属性

@property (nullable, nonatomic, readonly, copy) NSString *title;    //页面的title,终于可以直接获取了
@property (nullable, nonatomic, readonly, copy) NSURL *URL;     //当前webView的URL
@property (nonatomic, readonly, getter=isLoading) BOOL loading; //是否正在加载
@property (nonatomic, readonly) double estimatedProgress;   //加载的进度
@property (nonatomic, readonly) BOOL canGoBack; //是否可以后退,跟UIWebView相同
@property (nonatomic, readonly) BOOL canGoForward;  //是否可以前进,跟UIWebView相同

动态注入JS

给每个页面添加一个Cookie

//注入一个Cookie
WKUserScript *newCookieScript = [[WKUserScript alloc] initWithSource:@"document.cookie = 'DarkAngelCookie=DarkAngel;'" injectionTime:WKUserScriptInjectionTimeAtDocumentStart forMainFrameOnly:NO];
[controller addUserScript:newCookieScript];

然后再注入一个脚本,每当页面加载,就会alert当前页面cookie,在OC中的实现

//创建脚本
WKUserScript *cookieScript = [[WKUserScript alloc] initWithSource:@"alert(document.cookie);" injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:NO];
//添加脚本
[controller addUserScript:script];
OC -> JS
[self.webView evaluateJavaScript:@"document.title" completionHandler:^(id _Nullable title, NSError * _Nullable error) {
        NSLog(@"调用evaluateJavaScript异步获取title:%@", title);
}];
JS -> OC

1、URL拦截

- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler {
    //可以通过navigationAction.navigationType获取跳转类型,如新链接、后退等
    NSURL *URL = navigationAction.request.URL;
    //判断URL是否符合自定义的URL Scheme
    if ([URL.scheme isEqualToString:@"darkangel"]) {
        //根据不同的业务,来执行对应的操作,且获取参数
        if ([URL.host isEqualToString:@"smsLogin"]) {
            NSString *param = URL.query;
            NSLog(@"短信验证码登录, 参数为%@", param);
            decisionHandler(WKNavigationActionPolicyCancel);
            return;
        }
    }
    decisionHandler(WKNavigationActionPolicyAllow);
    NSLog(@"%@", NSStringFromSelector(_cmd));
}

2、WKScriptMessageHandler
OC中添加一个WKScriptMessageHandler,则会在all frames中添加一个js的function

(1)OC中监听JS的方法

// 监听JS的currentCookies方法
[controller addScriptMessageHandler:self name:@"currentCookies"]; //这里self要遵循协 WKScriptMessageHandler

(2)JS中调用下面的方法时

// JS调用currentCookies的时候写上这句代码
window.webkit.messageHandlers.currentCookies.postMessage(document.cookie);

(3)OC中将会收到WKScriptMessageHandler的回调

- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message {
    if ([message.name isEqualToString:@"currentCookies"]) {
        NSString *cookiesStr = message.body;    //message.body返回的是一个id类型的对象,所以可以支持很多种js的参数类型(js的function除外)
        NSLog(@"当前的cookie为: %@", cookiesStr);
    }
}

当然,记得在适当的地方调用removeScriptMessageHandler

- (void)dealloc {
    //记得移除
    [self.webView.configuration.userContentController removeScriptMessageHandlerForName:@"currentCookies"];
}
实现JS -> OC的调用,并且OC -> JS 异步回调结果,这里还是拿分享来举个例子

JS

/**
   * 分享方法,并且会异步回调分享结果
   * @param  {对象类型} shareData 一个分享数据的对象,包含title,imgUrl,link以及一个回调function
   * @return {void}  无同步返回值
   */
  function shareNew(shareData) {
    
    //这是该方法的默认实现,上篇文章中有所提及
    var title = shareData.title;
    var imgUrl = shareData.imgUrl;
    var link = shareData.link;
    var result = shareData.result;
    //do something
    //这里模拟异步操作
    setTimeout(function() {
        //2s之后,回调true分享成功
        result(true);
    }, 2000);

    //用于WKWebView,因为WKWebView并没有办法把js function传递过去,因此需要特殊处理一下
    //把js function转换为字符串,oc端调用时 (<js function string>)(true); 即可
    shareData.result = result.toString();
    window.webkit.messageHandlers.shareNew.postMessage(shareData);
  }

  function test() {
     //清空分享结果
    shareResult.innerHTML = "";
    
    //调用时,应该
    shareNew({
        title: "title",
        imgUrl: "http://img.dd.com/xxx.png",
        link: location.href,
        result: function(res) {
            //这里shareResult 等同于 document.getElementById("shareResult")
            shareResult.innerHTML = res ? "success" : "failure";
        }
    });
  }

在html页面中我定义了一个a标签来触发test()函数

<a href="javascript:void(0);" onclick="test()">测试新分享</a>

在OC端,实现如下

//首先别忘了,在configuration中的userContentController中添加scriptMessageHandler
[controller addScriptMessageHandler:self name:@"shareNew"]; //记得适当时候remove哦


//点击a标签时,则会调用下面的方法
#pragma mark - WKScriptMessageHandler 

- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message {
    if ([message.name isEqualToString:@"shareNew"]) {
        NSDictionary *shareData = message.body;
        NSLog(@"shareNew分享的数据为: %@", shareData);
        //模拟异步回调
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(4 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            //读取js function的字符串
            NSString *jsFunctionString = shareData[@"result"];
            //拼接调用该方法的js字符串
            NSString *callbackJs = [NSString stringWithFormat:@"(%@)(%d);", jsFunctionString, NO];    //后面的参数NO为模拟分享失败
            //执行回调
            [self.webView evaluateJavaScript:callbackJs completionHandler:^(id _Nullable result, NSError * _Nullable error) {
                if (!error) {
                    NSLog(@"模拟回调,分享失败");
                }
            }];
        });
    }
}

那么当我点击a标签时,html页面上过2s,会显示success,然后再过2s,会显示failure。

Cookie管理

    // 获取保存的cookies
    NSArray *cookies = [PSNetworkDataHelper cookiesForURL:url];
    
    // 每次都设置request的HTTPHeaderField
    NSDictionary *cookiesDict = [NSHTTPCookie requestHeaderFieldsWithCookies:cookies];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    [request setValue:[cookiesDict objectForKey:@"Cookie"] forHTTPHeaderField:@"Cookie"];
    
    
    // 每次都JS注入
    NSMutableString *cookiesString = [NSMutableString string];
    for (NSHTTPCookie *cookie in cookies) {
        NSString *string = [NSString stringWithFormat:@"%@=%@; ",cookie.name,cookie.value];
        [cookiesString appendFormat:@"document.cookie='%@';", string];
    }
    WKUserScript * cookieScript = [[WKUserScript alloc]
                                   initWithSource: cookiesString
                                   injectionTime:WKUserScriptInjectionTimeAtDocumentStart forMainFrameOnly:NO];
    
    [self.wkWebView.configuration.userContentController addUserScript:[self setCookie]];
    
    [self.wkWebView loadRequest:request];
使用WKWebView需要注意的地方
Cookie问题
JS弹窗,需要全部现实WKUIDelegate的代理
 #pragma mark - WKUIDelegate
- (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler{
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示" message:message?:@"" preferredStyle:UIAlertControllerStyleAlert];
    [alertController addAction:([UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        completionHandler();
    }])];
    [self presentViewController:alertController animated:YES completion:nil];
    
}
- (void)webView:(WKWebView *)webView runJavaScriptConfirmPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(BOOL))completionHandler{
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示" message:message?:@"" preferredStyle:UIAlertControllerStyleAlert];
    [alertController addAction:([UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        completionHandler(NO);
    }])];
    [alertController addAction:([UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        completionHandler(YES);
    }])];
    [self presentViewController:alertController animated:YES completion:nil];
}
- (void)webView:(WKWebView *)webView runJavaScriptTextInputPanelWithPrompt:(NSString *)prompt defaultText:(NSString *)defaultText initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(NSString * _Nullable))completionHandler{
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:prompt message:@"" preferredStyle:UIAlertControllerStyleAlert];
    [alertController addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
        textField.text = defaultText;
    }];
    [alertController addAction:([UIAlertAction actionWithTitle:@"完成" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        completionHandler(alertController.textFields[0].text?:@"");
    }])];
    [self presentViewController:alertController animated:YES completion:nil];
}
白屏问题

当WKWebView加载的网页占用内存过大时,会出现白屏现象。

解决:
A、借助 WKNavigtionDelegate: (void)webViewWebContentProcessDidTerminate:(WKWebView *)webView API_AVAILABLE(macosx(10.11), ios(9.0));回调函数:
当 WKWebView 总体内存占用过大,页面即将白屏的时候,系统会调用上面的回调函数,我们在该函数里执行[webView reload](这个时候 webView.URL 取值尚不为 nil)解决白屏问题。在一些高内存消耗的页面可能会频繁刷新当前页面,H5侧也要做相应的适配操作。
B、检测 webView.title 是否为空:在WKWebView白屏的时候,另一种现象是 webView.titile 会被置空, 因此,可以在 viewWillAppear 的时候检测 webView.title 是否为空来 reload 页面
导航栏半透明问题,能不用半透明就不用了,很折腾
上一篇下一篇

猜你喜欢

热点阅读