2

Similar to "How to detect if OS X is in dark mode in browsers?" only for JavaScript.

How to detect if the user's system is in the new macOS Dark Mode in Safari/Chrome/Firefox and get the result as a boolean value?

Finesse
  • 9,793
  • 7
  • 62
  • 92

1 Answers1

7

Use the matchMedia function to check the compliance with the prefers-color-scheme media rule:

const isDark = window.matchMedia('(prefers-color-scheme: dark)').matches;
// or
const isLight = window.matchMedia('(prefers-color-scheme: light)').matches;

You can also get a notification when the Dark Mode turns on/off:

const media = window.matchMedia('(prefers-color-scheme: dark)');

media.addListener(() => {
  alert(`The mode has changed to ${media.matches ? 'dark' : 'light'}`);
});
Finesse
  • 9,793
  • 7
  • 62
  • 92