Search code examples
swiftwebviewuiwebviewwebkitwkwebview

Disable the loading of Stylesheets in UIWebView and/or WKWebView


I have absolutely tried everything with this one. I've read every apple article and no where can I find how to disable the loading of CSS (Styling) in the legacy UIWebView or the new WKWebView. I don't mind what web view I use just as long as it can accomplish this.

I've tried WKPreferences() and WKWebViewConfiguration and both have no member userStyleSheetEnabled.

I've referred myself to this apple article https://developer.apple.com/documentation/webkit/webpreferences/1536396-userstylesheetenabled?

Does anyone know the answer and how to achieve this on Swift 4?


Solution

  • The WebView class you referenced is very old and has been deprecated. If you need to add a webview to your app, use WKWebView instead. This answer works with iOS >= 11 and macOS >= 10.13.

    What you need is adding WKContentRuleList to your WKWebView's configuration. They are similar to Safari content blockers (i.e. ad-blockers) that you may already have installed on your phone:

    // 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)
    }
    

    Result:

    Apple's website without stylesheet

    References