点击上方“iOS开发”,选择“置顶公众号”
关键时刻,第一时间送达!
作者:没故事的卓同学 來源:简书
文:https://www.jianshu.com/p/8af24e9dc82e
iOS开发整理发布,转载请联系作者获得授权
WKWebView中新增了一个功能,可以对WebView的内容添加一些自定义的过滤规则。这个功能原来在 Safari Extension 中被引入,从 11 开始同样适用于WKWebView。
使用方法
原理上就是提供一个 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!)
}
可使用的处理方式:Action
对应的 Action 有以下几种:
block
放弃加载资源,如果该资源已经缓存也忽略缓存block-cookies
所有发送的请求的header中都会过滤掉cookiecss-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 请求
规则触发器:trigger
触发器必须有url-filter
,可选的键有:resource-type
、if-domain
、unless-domain
url-filter
匹配 URL 的正则表达式if-domain 或者 unless-domain
if-domain:规则只在这些域名下起作用。unless-domain:这些域名除外。resource-type
资源的类型,对应的 value 有:
document
image
style-sheet
script
font
raw (Any untyped load, such as XMLHttpRequest)
svg-document
media
popup
load-type
资源的归属。默认是全部的资源。如果收到填有两种 value:
first-party
只有当资源和页面的scheme、域名、端口一致时才触发third-party
只有当资源和页面的域名不一致时才触发
举个 trigger 的示例就是:
"trigger": {
"url-filter": ".*",
"resource-type": ["image", "style-sheet"],
"unless-domain": ["your-content-server.com", "trusted-content-server.com"]
}
总结
可以通过配置规则拦截页面里的资源请求、隐藏页面里的指定元素、将http请求转换成https