参考博客:
iOS中UIWebView与WKWebView、JavaScript与OC交互、Cookie管理看我就够(中)
iOS UIWebView 和 WKWebView 的 cookie 获取,设置,删除
iOS11 WKWebView过滤规则WKContentRuleListStore
Webview加载H5优化小记
iOS 端 h5 页面秒开优化实践(使用WKURLSchemeHandler)
iOS WKWebView全部API解读
南华Coder -- WKWebview使用二三事
1、WKWebView
是Apple于iOS 8.0推出的WebKit中的核心控件,用来替UIWebView。
WKWebView比UIWebView的优势在于:
1、更多的支持HTML5的特性
2、高达60fps的滚动刷新率以及内置手势
3、与Safari相同的JavaScript引擎
4、将UIWebViewDelegate与UIWebView拆分成了14类与3个协议(官方文档说明)
5、更丰富的api与代理方法,比如可以获取加载进度: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相同
2、动态注入JS
(1)给每个页面添加一个Cookie
//注入一个Cookie
WKUserScript *newCookieScript = [[WKUserScript alloc] initWithSource:@"document.cookie = 'DarkAngelCookie=DarkAngel;'" injectionTime:WKUserScriptInjectionTimeAtDocumentStart forMainFrameOnly:NO];
[controller addUserScript:newCookieScript];
(2)然后再注入一个脚本,每当页面加载,就会alert当前页面cookie,在OC中的实现
//创建脚本
WKUserScript *cookieScript = [[WKUserScript alloc] initWithSource:@"alert(document.cookie);" injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:NO];
//添加脚本
[controller addUserScript:script];
(3)注入客户端的登录状态方法
NSString *app_isLogin = [NSString stringWithFormat:@"function app_isLogin(){return %i}",[ZYXAccountInfoManager sharedManager].isLogin];
WKUserScript *userScript = [[WKUserScript alloc] initWithSource:javaScriptSource injectionTime:WKUserScriptInjectionTimeAtDocumentStart forMainFrameOnly:YES];
[self.webView.configuration.userContentController addUserScript:userScript];
3、OC -> JS
[self.webView evaluateJavaScript:@"document.title" completionHandler:^(id _Nullable title, NSError * _Nullable error) {
NSLog(@"调用evaluateJavaScript异步获取title:%@", title);
}];
4、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) {
//用于WKWebView,因为WKWebView并没有办法把js function传递过去,因此需要特殊处理一下
//把js function转换为字符串,oc端调用时 (<js function string>)(true); 即可
var result = shareData.result;
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)(2 * 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标签时过2s,会显示failure。
5、Cookie管理
Cookie设置
(iOS11以前有些问题,各种方式都使用了,有些时候Cookie设置不上去)
///给webView注入cookie
if (@available(iOS 11.0, *)) {
WKHTTPCookieStore *cookieStore = self.webView.configuration.websiteDataStore.httpCookieStore;
// 取出保存的Cookie
NSData *data = [[NSUserDefaults standardUserDefaults] objectForKey:@"WKHTTPCookie"];
NSArray *cookies = [NSKeyedUnarchiver unarchiveObjectWithData:data];
for (int i=0; i< cookies.count; i++) {
[cookieStore setCookie:cookies[i] completionHandler:nil];
}
} else {
NSString *cookieString = [[NSUserDefaults standardUserDefaults] objectForKey:@"CookieString"];
//cookieString=@"aaaaaa=bbbb";
if (cookieString) {
// 多钟方式全都写上,不管了
// (1)第一种方式:request.setHTTPHeaderField
[request setValue:cookieString forHTTPHeaderField:@"Cookie"];
NSString *documentCookieString = [NSString stringWithFormat:@"document.cookie = '%@'",cookieString];
NSURL *targetURL = [NSURL URLWithString:@"https://test130-m.angsi.com"];
// (2)第二种方式
NSArray *headeringCookie = [NSHTTPCookie cookiesWithResponseHeaderFields:@{@"Set-Cookie":documentCookieString} forURL:targetURL];
[[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookies:headeringCookie forURL:targetURL mainDocumentURL:nil];
// (3)第三种方式
WKUserScript * cookieScript = [[WKUserScript alloc] initWithSource: documentCookieString injectionTime:WKUserScriptInjectionTimeAtDocumentStart forMainFrameOnly:NO];
[_webView.configuration.userContentController addUserScript:cookieScript];
}
}
[self.webView loadRequest:request];
Cookie获取保存
// 页面加载完成之后调用
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation{
//cookies获取存储
if (@available(iOS 11.0, *)) {
WKHTTPCookieStore *cookieStore = webView.configuration.websiteDataStore.httpCookieStore;
[cookieStore getAllCookies:^(NSArray<NSHTTPCookie *> * cookies) {
if (cookies.count >0 ) {
// 保存Cookie
NSData *data = [NSKeyedArchiver archivedDataWithRootObject:cookies];
[[NSUserDefaults standardUserDefaults] setObject:data forKey:@"WKHTTPCookie"];
[[NSUserDefaults standardUserDefaults] synchronize];
}
}];
} else {
// js获取
[webView evaluateJavaScript:[NSString stringWithFormat:@"document.cookie"] completionHandler:^(id _Nullable response, NSError * _Nullable error) {
if (response != 0) {
[[NSUserDefaults standardUserDefaults] setObject:response forKey:@"CookieString"];
[[NSUserDefaults standardUserDefaults] synchronize];
}
}];
}
}
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];
}
6、WKURLSchemeHandler实现拦截(iOS11)
拦截加载本地图片代码例子
WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];
[config setURLSchemeHandler:[[SchemeHandler alloc] init] forURLScheme:@"XXXXXScheme"];
NSURL *url = [NSURL URLWithString:@"XXXXXScheme://xxxx"];
NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url];
[webView loadRequest:request];
#import <Foundation/Foundation.h>
#import <WebKit/WebKit.h>
@interface SchemeHandler : NSObject<WKURLSchemeHandler>
@end
#import "SchemeHandler.h"
@implementation SchemeHandler
- (void)webView:(WKWebView *)webView startURLSchemeTask:(id <WKURLSchemeTask>)urlSchemeTask
{
UIImage *image = [UIImage imageNamed:@"photo"];
NSData *data = UIImageJPEGRepresentation(image, 1.0);
// 这里可以换成任何资源:image/jpg、text/html
[urlSchemeTask didReceiveResponse:[[NSURLResponse alloc] initWithURL:urlSchemeTask.request.URL MIMEType:@"image/jpg" expectedContentLength:data.length textEncodingName:nil]];
[urlSchemeTask didReceiveData:data];
[urlSchemeTask didFinish];
}
- (void)webView:(WKWebView *)webView stopURLSchemeTask:(id <WKURLSchemeTask>)urlSchemeTask;
{
urlSchemeTask = nil;
}
@end
7、使用WKWebView需要注意的地方
1、Cookie问题
2、白屏问题
当WKWebView加载的网页占用内存过大时,会出现白屏现象。
解决:
A、借助 WKNavigtionDelegate: (void)webViewWebContentProcessDidTerminate:(WKWebView *)webView API_AVAILABLE(macosx(10.11), ios(9.0));回调函数:
当 WKWebView 总体内存占用过大,页面即将白屏的时候,系统会调用上面的回调函数,我们在该函数里执行[webView reload](这个时候 webView.URL 取值尚不为 nil)解决白屏问题。在一些高内存消耗的页面可能会频繁刷新当前页面,H5侧也要做相应的适配操作。
// 白屏处理
- (void)webViewWebContentProcessDidTerminate:(WKWebView *)webView {
[webView reload]; //刷新就好了
}
B、检测 webView.title 是否为空:在WKWebView白屏的时候,另一种现象是 webView.titile 会被置空, 因此,可以在 viewWillAppear 的时候检测 webView.title 是否为空来 reload 页面
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
// 白屏处理
if (self.webView.title == nil) {
[self.webView reload];
}
}