从 iOS 11 开始,您可以使用WKContentRuleList
首先,创建内容规则或列表。每个规则都由触发器和操作组成。看Apple 关于内容规则创建的文档 https://developer.apple.com/library/content/documentation/Extensions/Conceptual/ContentBlockingRules/CreatingRules/CreatingRules.html
这是一个创建示例,阻止所有图像和样式表内容,但允许那些以jpeg通过忽略前面的规则:
let blockRules = """
[{
"trigger": {
"url-filter": ".*",
"resource-type": ["image"]
},
"action": {
"type": "block"
}
},
{
"trigger": {
"url-filter": ".*",
"resource-type": ["style-sheet"]
},
"action": {
"type": "block"
}
},
{
"trigger": {
"url-filter": ".*.jpeg"
},
"action": {
"type": "ignore-previous-rules"
}
}]
"""
有了规则列表,您可以将它们添加到 ContentRuleListStore
import WebKit
@IBOutlet weak var wkWebView: WKWebView!
let request = URLRequest(url: URL(string: "https://yourSite.com/")!)
WKContentRuleListStore.default().compileContentRuleList(
forIdentifier: "ContentBlockingRules",
encodedContentRuleList: blockRules) { (contentRuleList, error) in
if let error = error {
return
}
let configuration = self.webView.configuration
configuration.userContentController.add(contentRuleList!)
self.wkWwebView.load(self.request)
}
如果稍后您想删除所有规则,请致电:
self.wkWebView.configuration.userContentController.removeAllContentRuleLists()
self.wkWebView.load(self.request)
这里是2017年WWDC视频 https://developer.apple.com/videos/play/wwdc2017/220/
祝你好运!
我创建了一个示例项目Github 上的 WKContentRule 示例 https://github.com/dequin-cl/WKContentRuleExample