1. Miscellaneous
  2. Reacting to Operating System Theme Preferences

Miscellaneous

Reacting to Operating System Theme Preferences

While it's always good to respect a user's theme preferences, it's especially important for desktop apps as a user's theme will affect the style of your app's window frame. There are a couple of options available to us when reacting to theme preferences.

Using CSS to react to theme preferences

CSS provides a prefers-color-scheme media feature which allows us to detect if a user is using dark or light color themes based on their system settings:

        @media (prefers-color-scheme: dark) {
  body {
    background-color: black;
  }
}

@media (prefers-color-scheme: light) {
  body {
    background-color: white;
  }
}

      

Using JavaScript to react to theme preferences

You can also detect theme settings with JavaScript, using the window.matchMedia utility:

        function reactToThemeMode() {
  const isDarkMode = window.matchMedia('(prefers-color-scheme: dark)').matches;
  document.body.classList.toggle('dark', isDarkMode);
  document.body.classList.toggle('light', !isDarkMode);
}

reactToThemeMode();

      

To react when a user changes these settings, we can place an event listener on the return value of window.matchMedia:

        const media = window.matchMedia('(prefers-color-scheme: dark)');
media.addEventListener('change', () => reactToThemeMode());

      

Overriding Theme Preferences

While a user can specify theme settings at an operating system level, there are situations where they may want to override this choice for specific apps. In these situations, it's important to also change the theme at the window level, because a user's theme preferences should also affect the window frame.

This can be achieved using the @todesktop/client-core library:

        npm install @todesktop/client-core

      

With that library installed, we can update both the application and native theme:

        import { nativeTheme, platform } from '@todesktop/client-core';

async function changeAppThemeMode(isDarkMode) {
  // change theme mode as normal
  document.body.classList.toggle('dark', isDarkMode);
  document.body.classList.toggle('light', !isDarkMode);

  // if within a desktop app, also change the native theme for the window
  if (platform.todesktop.isDesktopApp()) {
    await nativeTheme.setThemeSource(isDarkMode ? 'dark' : 'light');
  }
}

      
INFO

The platform.todesktop.isDesktopApp() function will ensure that the code only runs within the context of a desktop app. For more information on using custom JavaScript in ToDesktop apps, see our detailed guide.