androidandroid-webview

How to force dark web pages in android webview?


If we enable chrome://flags/#enable-force-dark flag in chrome browser on android then web page becomes dark.

I want to achieve similar thing (i.e. dark web ui) in android webview.

Currently I am using following code:

  private void injectCSS() {
        
       String code = "javascript:(function() {" +
                 "var node = document.createElement('style');"+
                 "node.type = 'text/css';"+
                   " node.innerHTML = 'body, label,th,p,a, td, tr,li,ul,span,table,h1,h2,h3,h4,h5,h6,h7,div,small {"+
                   "     color: #deFFFFFF;"+
                        "background-color: #232323;"+
                   " } ';"+
                   " document.head.appendChild(node);})();";

        webView.evaluateJavascript(code,null);
     
    }

I run this code in:

    @Override
    public void onProgressChanged(WebView view, final int 
            newProgress) {
              super.onProgressChanged(view, newProgress);
              injectCSS();
             }

    @Override
    public void onPageStarted(final WebView view, String url, 
       Bitmap favicon) {
             injectCSS();
             super.onPageStarted(view, url, favicon);    
      }

   @Override
    public void onPageFinished(WebView view, final String url) 
      {
          injectCSS();
          super.onPageFinished(view, url);
      }

Now I get near about same dark web pages like chrome. But I want to improve this code because it has some issues like anchor links not gets displayed properly. Suggest any better technique (if available)


Solution

  • If you see androidx.webkit:webkit:1.3.0-beta01 change logs 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 -

    Apply it accordingly using setForceDark function-

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