title: Letting WebView on Android work with prefers-color-scheme: dark
body: <p>I have an Android App that uses webview, and lately I'm trying to figure out how to add a dark theme by using the new <code>@media (prefers-color-scheme: dark)</code> CSS syntax.  I have the correct CSS written on my page, and if I open it in Chrome with the dark mode of Chrome turning on, it works. I also have my <code>AppTheme</code> inheriting <code>Theme.AppCompat.DayNight</code>, and my app shows dark loading dialog etc. when I turn on dark mode for the entire OS on my device. Even the auto-complete options for the <code>&lt;input&gt;</code> elements become dark. But still, the webpage loaded with my webview doesn't turn dark. According to <a href="https://developer.mozilla.org/en-US/docs/Web/CSS/@media/prefers-color-scheme" rel="noreferrer">this page</a>, webviews should support this feature, but I just can't get it to work. What am I missing here?</p>
  
  <p>I also just found out that in API 29 there's this <code>WebSettings.setForceDark()</code> method; could it be the thing I'm looking for? I hope to find a solution that works with lower API level though.</p>
  
  <p>By the way, my current workaround is to inject a JavaScript interface like this:</p>
  
  <pre class="lang-java prettyprint-override"><code>webView.addJavascriptInterface(new JSInterface(), "jsInterface");
  
  ...
  
  public class JSInterface {
      @JavascriptInterface
      public boolean isNightMode() {
          int nightModeFlags = getResources().getConfiguration().uiMode &amp; Configuration.UI_MODE_NIGHT_MASK;
          return nightModeFlags == Configuration.UI_MODE_NIGHT_YES;
      }
  }
  </code></pre>
  
  <p>And then in my webpage, call the <code>jsInterface.isNightMode()</code> method and dynamically load different CSS file based on the result. It certainly works and responses to the global dark mode setting as desired, but I still wonder if I can make <code>prefers-color-scheme</code> work.</p>