问题描述
我有一个可加载网页但阻止下载图像,字体,javascript等的应用程序.为此,我实现了一个NSURLProtocol
子类,该子类与UIWebView很好地兼容.
I have an app that loads a webpage, but prevents the downloads of images, fonts, javascripts, etc. For this I implemented an NSURLProtocol
subclass which works very well with UIWebView.
但是,我要迁移到WKWebview
,并且意识到我精心制作的NSURLProtocol
类不再能过滤掉这些资源.
However I'm migrating to WKWebview
, and realise that my crafted NSURLProtocol
class no longer works to filter out these resources.
有没有人知道如何实现过滤/阻止?
Have anyone an insight as to how to achive the filtering/blocking?
如果您想知道如何进行迁移,请从这篇文章开始: http://floatlearning.com/2014/12/uiwebview-wkwebview-and-tying-them-together-using-swift/
In case you're wondering how am I doing the migration, I started with this post: http://floatlearning.com/2014/12/uiwebview-wkwebview-and-tying-them-together-using-swift/
推荐答案
自iOS 11开始,您可以使用WKContentRuleList
Since iOS 11 you can use WKContentRuleList
首先,创建内容规则或列表.每个规则都包含一个触发器和一个动作.看 Apple的内容规则创建文档
First, create a Content Rule or a list. Each rule is comprised of a trigger and an action. SeeApple's Documentation on Content Rule creation
这是一个创建示例,它阻止所有图像和样式表内容,但是通过忽略以前的规则,允许那些以 jpeg 结尾的内容:
This is a creation example, blocks all image and Style Sheet content, but allows those ended on jpeg by way of ignoring the previous rules:
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
Having your list of rules, you can add them to the 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)
}
如果以后要删除所有规则,请致电:
If later you want to remove all your rules, call:
self.wkWebView.configuration.userContentController.removeAllContentRuleLists()
self.wkWebView.load(self.request)
这是 2017年WWDC视频
好运!
我已经在Github WKContentRuleExample上创建了一个示例项目
I've created a sample project on Github WKContentRuleExample
这篇关于如何阻止外部资源加载到WKWebView上?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!