Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WKWebView Dark and Light Mode with dynamic URL in Swift 5

I created WKWebView that doesn't have one url. User use this WKWebView as Safari means user can search anything on WKWebView. I am facing one issue when I change dark and light mode my web view will show me only white(Light) mode. My app is working on both mode all things working fine except WKWebView.

Already search on SO not find any related question on this. how to use iOS 13 darkmode for wkwebview

I refer this blog but it's static url so it will not help me out

https://useyourloaf.com/blog/using-dynamic-type-with-web-views/

Also checked opaque and background property but not working for me!

IMPORTANT User can search anything like google.com, photos or any surfing etc.

class DownloadViewController: UIViewController {
    
    @IBOutlet weak var webView: WKWebView!

    override func viewDidLoad() {
        super.viewDidLoad()
        webView.uiDelegate = self
        webView.navigationDelegate = self
        webView.load(URLRequest(url: URL(string: "https://www.google.com")!))
        webView.allowsBackForwardNavigationGestures = true
        webView.allowsLinkPreview = true
    }

}

First I am loading Google site then depend on user(Totally dynamic not one url here).

Please suggest me! Thank you.

like image 941
Yogesh Patel Avatar asked Aug 31 '25 18:08

Yogesh Patel


1 Answers

You can use injecting CSS technic to add Light/Dark feature to your loaded web pages e.g:

// Load a web page
webView?.load(URLRequest(url: URL(string: "https://google.com")!))

// Inject Light/Dark CSS

let lightDarkCSS = ":root { color-scheme: light dark; }"
let base64 = lightDarkCSS.data(using: .utf8)!.base64EncodedString()

let script = """
    javascript:(function() {
        var parent = document.getElementsByTagName('head').item(0);
        var style = document.createElement('style');
        style.type = 'text/css';
        style.innerHTML = window.atob('\(base64)');
        parent.appendChild(style);
    })()
"""

let cssScript = WKUserScript(source: script, injectionTime: .atDocumentEnd, forMainFrameOnly: false)
webView?.configuration.userContentController.addUserScript(cssScript)

Result:

WKWebView: Google dark mode

To support page changing you can move insertion code to didCommitNavigation notification:

func webView(_ webView: WKWebView, didCommit navigation: WKNavigation!) {
    ...
    // Inject CSS here
}

NOTE: It doesn't work with any web page in general because some of web sites can hardcode colors of background, fonts etc. but you can tune specific pages as well by overriding its CSS.

like image 77
iUrii Avatar answered Sep 02 '25 12:09

iUrii