禁止在 UIWebView 中加载样式表 and/or WKWebView

Disable the loading of Stylesheets in UIWebView and/or WKWebView

我已经用这个尝试了一切。我已经阅读了所有 Apple 文章,但没有在哪里可以找到如何在旧版 UIWebView 或新 WKWebView 中禁用 CSS(样式)的加载。我不介意我使用什么 web 视图,只要它能完成这个。

我试过 WKPreferences()WKWebViewConfiguration,但都没有成员 userStyleSheetEnabled。

我已参考这篇苹果文章 https://developer.apple.com/documentation/webkit/webpreferences/1536396-userstylesheetenabled?

有人知道答案以及如何在 Swift 4 上实现吗?

您引用的 WebView class 非常旧,已被弃用。如果您需要将网络视图添加到您的应用程序,请改用 WKWebView。此答案适用于 iOS >= 11 和 macOS >= 10.13.

您需要将 WKContentRuleList 添加到 WKWebView 的配置中。它们类似于您可能已经安装在 phone:

上的 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)
}

结果:

参考资料