在 WKWebview 中更改 google CSS

Change google CSS in WKWebview

我正在尝试在我的 WKWebview

中将 google 的背景颜色设置为红色

它短暂地闪烁红色,然后当 google 加载时背​​景变为白色。

代码:

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

为什么背景不保持红色?

Coordinator 中评估 JS(设置为 WKWebView 委托)

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

}