WKWebView中新增了一个功能,可以对WebView的内容添加一些自定义的过滤规则。这个功能原来在 Safari Extension 中被引入,从 11 开始同样适用于WKWebView。
使用方法
原理上就是提供一个 JSON 给 WebKit,这个 JSON 包括内容的触发规则(trigger)和对应的处理方式(action)。比如:
? 1 2 3 4 5 6 [{ "trigger": { "url-filter": ".*" }, "action": { "type": "make-https"} }]WebKit 会把拦截规则编译成高效的二进制码。使用方法如下:
? 1 2 3 4 5 6 7 8 9 WKContentRuleListStore.default().compileContentRuleList( forIdentifier: "ContentBlockingRules", encodedContentRuleList: jsonString) { (contentRuleList, error) in if let error = error { return } let configuration = WKWebViewConfiguration() configuration.userContentController.add(ruleList!) }可使用的处理方式:Action
对应的 Action 有以下几种:
规则触发器:trigger
触发器必须有url-filter,可选的键有:resource-type、if-domain、unless-domain
举个 trigger 的示例就是:
? 1 2 3 4 5 "trigger": { "url-filter": ".*", "resource-type": ["image", "style-sheet"], "unless-domain": ["your-content-server.com", "trusted-content-server.com"] }总结
可以通过配置规则拦截页面里的资源请求、隐藏页面里的指定元素、将http请求转换成https。
参考
Content Blocking Rules
WWDC 17:customized_loading_in_wkwebview
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。
原文链接:http://www.jianshu.com/p/8af24e9dc82e