WebView darkening — Force Dark Mode for Web Contents

Anoop M Madasseri
Tech Log
Published in
2 min readJun 24, 2020

Now you can automatically render all web contents using a dark theme in Android WebView. If you see androidx.webkit:webkit:1.3.0-beta01 changelogs you could see ForceDark API added to control if WebView should be rendered in dark mode. You can use ForceDarkStrategy API to control WebView darkening (CSS/web content darkening versus auto-darkening).

Prior try to access this feature, ensure that it is supported by the Webview is being used in. For this, the WebViewFeature class have an isFeatureSupported() function, which can be used to check if a given feature is supported. So before we go ahead and set the support for dark mode check if it is supported:

if (WebViewFeature.isFeatureSupported(WebViewFeature.FORCE_DARK)) { ... }

There are 3 different constants available in WebSettingsCompat to configure

  • FORCE_DARK_OFF — Disable the force dark mode for the webview, meaning the content of the webview will be rendered as-is
  • FORCE_DARK_ON — Enable the force dark mode for the webview, meaning the content of the webview will always be rendered with a dark theme
  • FORCE_DARK_AUTO — Enable the force dark mode for the webview depending on the state of the parent view, meaning that the system dark mode setting will be followed when rendering the content of the webview.

Apply it accordingly using setForceDark function-

WebSettingsCompat.setForceDark(webView.settings, WebSettingsCompat.FORCE_DARK_ON)

Note: The setForceDark fun requires Android System WebView Version 76 or/+ to be installed on the device. There is no other straight forward way to enable dark mode in WebView if it doesn’t support. This is a major problem for the apps that uses a dark theme. OTOH, If you want to support WebView that doesn’t support dark theme google’s recommendation is to modify your WebView content with custom styling for Dark Theme. The prefers-color-scheme: dark @media query provides developers with a way to define custom styling for a Dark Theme similar to the way Android allows you to provide night-conditional resources.

--

--