-1

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.

Sam Herrmann
  • 6,293
  • 4
  • 31
  • 50
AGamePlayer
  • 7,404
  • 19
  • 62
  • 119

2 Answers2

2

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.

Sam Herrmann
  • 6,293
  • 4
  • 31
  • 50
0

The issue is that it doesn't throw an error when it doesn't match.

if (window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches) {
      // dark mode
  } else { alert('do not support dark mode'); }