WKWebView中新增了一个功能,可以对WebView的内容添加一些自定义的过滤规则。这个功能原来在 Safari Extension 中被引入,从 11 开始同样适用于WKWebView。
[b]使用方法[/b]
原理上就是提供一个 JSON 给 WebKit,这个 JSON 包括内容的触发规则(trigger)和对应的处理方式(action)。比如:
[{
"trigger": {
"url-filter": ".*" },
"action": {
"type": "make-https"}
}]
WebKit 会把拦截规则编译成高效的二进制码。使用方法如下:
WKContentRuleListStore.default().compileContentRuleList(
forIdentifier: "ContentBlockingRules",
encodedContentRuleList: jsonString) { (contentRuleList, error) in
if let error = error {
return
}
let configuration = WKWebViewConfiguration()
configuration.userContentController.add(ruleList!)
}
[b]可使用的处理方式:Action[/b]
对应的 Action 有以下几种:
[list=1]
[*]block:放弃加载资源,如果该资源已经缓存也忽略缓存[/*]
[*]block-cookies:所有发送的请求的header中都会过滤掉cookie[/*]
[*]css-display-none:隐藏使用 CSS selector 的页面元素,同时还有关联的selector:
"action": {
"type": "css-display-none",
"selector": "#newsletter, :matches(.main-page, .article) .news-overlay"
}
[/*]
[*]ignore-previous-rules:前面触发的规则不执行[/*]
[*]make-https:把网页里的 http 请求改为 https 请求[/*]
[/list]
[b]规则触发器:trigger[/b]
触发器必须有url-filter,可选的键有:resource-type、if-domain、unless-domain
[list=1]
[*]url-filter 匹配 URL 的正则表达式[/*]
[*]if-domain 或者 unless-domain if-domain:规则只在这些域名下起作用。unless-domain:这些域名除外。[/*]
[*]resource-type 资源的类型,对应的 value 有:
[list=1]
document[/*]
[*]image[/*]
[*]style-sheet[/*]
[*]script[/*]
[*]font[/*]
[*]raw (Any untyped load, such as XMLHttpRequest)[/*]
[*]svg-document[/*]
[*]media[/*]
[*]popup[/*]
[/list]
[*]load-type 资源的归属。默认是全部的资源。如果收到填有两种 value:
[list=1]
first-party 只有当资源和页面的scheme、域名、端口一致时才触发[/*]
[*]third-party 只有当资源和页面的域名不一致时才触发[/*]
[/list]
[/list]
举个 trigger 的示例就是:
"trigger": {
"url-filter": ".*",
"resource-type": ["image", "style-sheet"],
"unless-domain": ["your-content-server.com", "trusted-content-server.com"]
}
[b]总结[/b]
可以通过配置规则拦截页面里的资源请求、隐藏页面里的指定元素、将http请求转换成https。
[b]参考[/b]
[url=https://developer.apple.com/library/content/documentation/Extensions/Conceptual/ContentBlockingRules/CreatingRules/CreatingRules.html]Content Blocking Rules [/url]
[url=https://developer.apple.com/videos/play/wwdc2017/220/]WWDC 17:customized_loading_in_wkwebview[/url]
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持编程素材网。