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.
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:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With