WKWebView in SwiftUI iOS 14 and Xcode 12

I have code that loads an HTML page into a WKWebView and needs to call javascript functions in the HTML page to update font family and size.

Now that WKPreferences.javaScriptEnabled has been deprecated, it does not seem to work anymore.

How to I correctly create a struct WebView: UIViewRepresentable with makeUIView and updateUIView to be able to show the page and call the functions in the HTML page?

Please help...

I am in a similar boat where I have a SwiftUI app that wraps a WKWebView in UIViewRepresentable.

For your goal of updating font-family and size, I am using a WKUserScript to inject custom CSS to change the font-family and size. This is working OK for me on both iOS 13 and 14. Sample code that creates my WKWebView in my UIViewRepresentable class.:

Code Block swift
    lazy var webView: WKWebView = {
        guard let path = Bundle.main.path(forResource: "style", ofType: "css"),
          let cssString = try? String(contentsOfFile: path).components(separatedBy: .newlines).joined()
        else {
          return WKWebView()
        }
        let source = """
           var style = document.createElement('style');
           style.innerHTML = '\(cssString)';
           document.head.appendChild(style);
        """
        let userScript = WKUserScript(source: source, injectionTime: .atDocumentEnd, forMainFrameOnly: true)
        let userContentController = WKUserContentController()
        userContentController.addUserScript(userScript)
        let configuration = WKWebViewConfiguration()
        configuration.userContentController = userContentController
        let webView = WKWebView(frame: .zero, configuration: configuration)
        return webView
    }()


However, I have a different problem - now my WKWebView doesn't render for about 30 seconds on iOS 14. I have no idea, and stumbled upon this question trying to research an answer. Let me know if you have encountered this.

I ran into an issue where I am calling WkWebview.evaluateJavaScript:@"navigator.userAgent" and it is taking 20 seconds to return in Beta 4. Maybe that is what you are running into.
Seems to work OK if you are running on Big Sur
WKWebView in SwiftUI iOS 14 and Xcode 12
 
 
Q