How can I use Node.js/Electron to determine Windows 10 Dark Mode?

Viewed 1329

The Windows 10 Anniversary Update introduced a dark mode, where most supporting apps will change their color palette to be dark. I want to use Node.js or Electron to determine whether or not that setting is enabled, so I can appropriately choose which theme to start my app with by default. What's the best way to do this?

3 Answers

Starting from electron 6.0.0 (and chromium 76) media query prefers color scheme can be used to detect dark/light mode like this:

@media screen and (prefers-color-scheme: light), screen and (prefers-color-scheme: no-preference) {
    /*light theme*/
  body{
    color: black;
    background-color: white;
  }
}

@media screen and (prefers-color-scheme: dark) {
    /*dark theme*/
  body {
    color: white;
    background-color: black;
  }
}

You can also check for dark mode programatically as follows:

if (window.matchMedia('(prefers-color-scheme:dark)').matches) {
    console.log('dark');
}
else {
    console.log('light or no-preference');
}

Demo: codepen

One option I could think of would be to read the following registry key: HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Themes\Personalize\AppsUseLightTheme

Expanding upon @Ambar answer, it is possible to listen to media change events programmatically and keep track of the system theme color mode in the following manner:

let systemThemeColorModeQuery = window.matchMedia('(prefers-color-scheme:dark)');

systemThemeColorModeQuery.onchange = (event) => {
  if (event.matches) {
    /* System color mode changed to DARK MODE */
  } else {
    /* System color mode changed to LIGHT MODE */
  }
}
Related