【问题标题】:Disable the loading of Stylesheets in UIWebView and/or WKWebView禁用 UIWebView 和/或 WKWebView 中样式表的加载
【发布时间】:2018-04-27 12:52:40
【问题描述】:
【问题讨论】:
标签:
swift
webview
uiwebview
webkit
wkwebview
【解决方案1】:
您引用的WebView 类非常旧,已被弃用。如果您需要向您的应用添加 web 视图,请改用 WKWebView。此答案适用于 iOS >= 11 和 macOS >= 10.13。
您需要将WKContentRuleList 添加到您的WKWebView 的配置中。它们类似于您可能已经在手机上安装的 Safari 内容拦截器(即广告拦截器):
// This should ideally be in a file but we're using string for convenience
let jsonRuleList = """
[{
"trigger": {
"url-filter": ".*",
"resource-type": ["style-sheet"]
},
"action": {
"type": "block"
}
}]
"""
// Compile the content-blocking list
WKContentRuleListStore.default().compileContentRuleList(forIdentifier: "blockStyleSheet", encodedContentRuleList: jsonRuleList) { list, error in
guard error == nil else { print(error!.localizedDescription); return }
guard let list = list else { return }
// Add the stylesheet-blocker to your webview's configuration
let configuration = WKWebViewConfiguration()
configuration.userContentController.add(list)
// Adding the webview to the view. Nothing to see here
self.webView = WKWebView(frame: self.view.bounds, configuration: configuration)
self.view.addSubview(self.webView)
// Let's try Apple's website without CSS
let request = URLRequest(url: URL(string: "https://www.apple.com")!)
self.webView.load(request)
}
结果:
参考文献