【问题标题】:Disable the loading of Stylesheets in UIWebView and/or WKWebView禁用 UIWebView 和/或 WKWebView 中样式表的加载
【发布时间】:2018-04-27 12:52:40
【问题描述】:

我已经用这个绝对尝试过一切。我已经阅读了每篇苹果文章,但在哪里可以找到如何在旧版 UIWebView 或新 WKWebView 中禁用 CSS(样式)的加载。我不介意我使用什么 Web 视图,只要它可以完成此操作即可。

我试过WKPreferences()WKWebViewConfiguration 都没有用户userStyleSheetEnabled。

我已经把自己推荐给了这篇苹果文章https://developer.apple.com/documentation/webkit/webpreferences/1536396-userstylesheetenabled?

有谁知道答案以及如何在 Swift 4 上实现这一目标?

【问题讨论】:

    标签: 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)
    }
    

    结果:

    参考文献

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-11-25
      • 1970-01-01
      • 1970-01-01
      • 2017-03-22
      • 1970-01-01
      • 2016-01-12
      • 1970-01-01
      • 2015-12-05
      相关资源
      最近更新 更多