1

I have successfully obtained darkmode effect for random HTML on a website html page using source from this great tutorial.

I have uploaded these photos to explain better what I obtained. Random html loaded

Darkmode applied

I am trying to obtain the same on a WKWebView. The HTML is loaded from an API so I use the WKWebView.loadHTMLString method. For this example the demo HTML is saved in a file in the Xcode project. Also I've added 2 javascript files in Xcode: darkmode.min.js (which is the library) and darkmode-options.js (the position and text label for the toggle in the bottom of the page). I think that I do not inject correctly the 2 scripts using WKUserScript. Obviously the darkmode.min.js must be loaded before darkmode-options.js. That is why I used WKUserScriptInjectionTime.atDocumentStart and WKUserScriptInjectionTime.atDocumentEnd.

Also when I print in the console the view source of the HTML, it does not show the scripts that have been inserted.

 private func initWebView() {

    let html = self.demoHTML
    let jsLibrary = self.darkModeLibraryJS
    let jsOptions = self.darkModeOptionsJS

    let webConfiguration = WKWebViewConfiguration()
    let contentController = WKUserContentController()

    // Libray script an document start
    let userScript = WKUserScript(source: jsLibrary, injectionTime: WKUserScriptInjectionTime.atDocumentStart, forMainFrameOnly: false)
    contentController.addUserScript(userScript)

    // Options script and document end
    let optionsScript = WKUserScript(source: jsOptions, injectionTime: WKUserScriptInjectionTime.atDocumentEnd, forMainFrameOnly: false)
    contentController.addUserScript(optionsScript)

    webConfiguration.userContentController = contentController


    self.webview = WKWebView(frame: CGRect.zero, configuration: webConfiguration)
    self.webview?.navigationDelegate = self
    self.view.addSubview(webview!)

    self.webview!.loadHTMLString(html, baseURL: nil)
    self.webview!.fillSuperview() // after view has been added as subview
}

func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
    self.chechHTML()
}

private func chechHTML() {

    let script = "document.documentElement.outerHTML.toString()"

    self.webview?.evaluateJavaScript(script, completionHandler: { (html, error) in

        if html != nil {
            print("❌: check html response", html ?? "")
        }
        if error != nil {
            print("❌: check html with error", error ?? "")
        }
    })
}

The project is uploaded on github: https://github.com/CristiGhn/darkmode-webview. The Xcode project also contains a darkmode.html that works and shows the exact as the photos above.

Thank you!

4

1 に答える 1