Change google CSS in WKWebview

Viewed 268

I'm trying to set the background color to red for google in my WKWebview

It flashes red for a brief moment, then when google loads the background goes white.

Code:

struct WebContentView: View {
    var searchQuery: String
    
    var body: some View {
        let encodedQuery = searchQuery.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)
        WebView(urlString: "https://google.com/search?q=" + encodedQuery!)
    }
}

struct WebView: UIViewRepresentable {
    let urlString: String?
    
    func makeUIView(context: Context) -> WKWebView {
        return WKWebView()
    }
    
    func updateUIView(_ uiView: WKWebView, context: Context) {
        if let safeString = urlString, let url = URL(string: safeString) {
            let request = URLRequest(url: url)
            uiView.load(request)
            
            let css = "body { background-color : #ff0000 }"
            let js = "var style = document.createElement('style'); style.innerHTML = '\(css)'; document.head.appendChild(style);"
            
            uiView.evaluateJavaScript(js, completionHandler: nil)
        }
    }
}

Why doesn't the background stay red?

1 Answers

Evaluate JS in a Coordinator (set up as WKWebView delegate)

struct WebView: UIViewRepresentable {
    let urlString: String?
    
    func makeUIView(context: Context) -> WKWebView {
        let webView = WKWebView()
        webview.navigationDelegate = context.coordinator    // << delegate !!
        return webView
    }
    
    func updateUIView(_ uiView: WKWebView, context: Context) {
        if let safeString = urlString, let url = URL(string: safeString) {
            let request = URLRequest(url: url)
            uiView.load(request)
        }
    }

    class Coordinator: NSObject, WKNavigationDelegate {

        func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
            let css = "body { background-color : #ff0000 }"
            let js = "var style = document.createElement('style'); style.innerHTML = '\(css)'; document.head.appendChild(style);"
            
            webView.evaluateJavaScript(js, completionHandler: nil)   // << here !!
        }
    }

    func makeCoordinator() -> Coordinator {
        Coordinator()
    }

}
Related