iOS11中WKWebview得到了加强,添加了三种开发者呼声比较大的功能,分别是:
- Manage Cookie(Cookie 管理)
- Filter Unwanted Content (过滤不需要的内容)
- Provide Custom Resource (提供自定义的资源内容)
Manager Cookie
在iOS11前,要对Cookie进行管理只能在WKWebview初始化前自定义UserScript执行JS方法进行Cookie设置,代码大概如下:
WKWebViewConfiguration *webConfig = [[WKWebViewConfiguration alloc] init];
// 设置偏好设置
webConfig.preferences = [[WKPreferences alloc] init];
// 默认为0
webConfig.preferences.minimumFontSize = 10;
// 默认认为YES
webConfig.preferences.javaScriptEnabled = YES;
// 在iOS上默认为NO,表示不能自动通过窗口打开
webConfig.preferences.javaScriptCanOpenWindowsAutomatically = NO;
// web内容处理池
webConfig.processPool = [[WKProcessPool alloc] init];
// 将所有cookie以document.cookie = 'key=value';形式进行拼接
#warning 然而这里的单引号一定要注意是英文的,不要问我为什么告诉你这个(手动微笑)
NSString *cookieValue = @"document.cookie = 'fromapp=ios';document.cookie = 'channel=appstore';";
// 加cookie给h5识别,表明在ios端打开该地址
WKUserContentController* userContentController = WKUserContentController.new;
WKUserScript * cookieScript = [[WKUserScript alloc]
initWithSource: cookieValue
injectionTime:WKUserScriptInjectionTimeAtDocumentStart forMainFrameOnly:NO];
[userContentController addUserScript:cookieScript];
webConfig.userContentController = userContentController;
WKWebView *wkWebView = [[WKWebView alloc] initWithFrame:frame configuration:webConfig];
wkWebView.UIDelegate = wkWebView;
wkWebView.navigationDelegate = wkWebView;
但在iOS11中,WKWebview提供新的属性
let cookieStore = webView.configuration.websiteDataStore.httpCookieStore;
其提供的功能如下:
- Add and remove individual Cookies 添加删除指定的Cookie
- Access all cookies visible to a WKWebview 访问WKWebview的所有Cookies
- Including HTTP-Only Cookies
- Observer the cookie store for changes 观察Cookie Store的变化
添加Cookie

删除Cookie

遍历Cookie

Filter Unwanted Content
WKWebview实现内容过滤的方法和Safari的内容过滤扩展的方法类似,都是使用了ContentRuleList的东西,这个RuleList的主要功能有
- Block Loads 拦截加载
- Make Content Invisible 使内容不可见
- Make Insecure Loads Secure 使不安全的加载变得安全
使用时先把内容过滤的要求写成JSON格式

然后调用WKContentRuleListStore的方法把它转为字节码

这样WKWebview在加载内容时候会按照定义好的Rule去执行
可以通过以下方法遍历指定名字的RuleList

Provide Custom Resource
在iOS11中,对于WKWebview可以注册指定的Scheme并设定回调对象,当WKWebview遇到这些指定的Scheme的请求,它会让回调对象处理这个请求,从而实现返回自定义的内容
注册Scheme

Handler需要实现WKURLSchemeHandler协议

在协议中传入的参数都实现了WKURLSchemeTask协议

返回自定义的内容
在WKURLSchemeHandler协议的实现方法中,一般都是取出Request信息,然后根据需求生成自定义的内容,再调用WKURLSchemeTask对象的didReceiveData和didReceiveResponse的方法等完成一个具体请求

网友评论