Search code examples
javascriptcssdarkmode

Is there a way to know whether the OS supports dark mode in a web page? (by JavaScript, CSS)


Is there anything like CSS.supports('dark-mode') ?

I tried this:

try {

  if (window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches) {
      // dark mode
  }

} catch (e) {
  alert('do not support dark mode');
}

But the alert would never run.


Solution

  • alert doesn't run because there is nothing in your try-block that throws an error. The if-condition returns true/false, which means you need a simple if/else-statement:

    
    if (window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches) {
       // dark mode
    } else {
      // light mode
    }
    
    

    If you need to detect if the media query string prefers-color-scheme is supported by the browser, then you may have to explicitly check for both light and dark:

    function isPreferredColorSchemeSupported() {
      return (
        window.matchMedia &&
        (window.matchMedia('(prefers-color-scheme: light)').matches ||
          window.matchMedia('(prefers-color-scheme: dark)').matches)
      );
    }
    

    If false is returned, then you know that the browser didn't match the light or the dark media query, from which you can infer that the browser didn't understand the media query.