A plugin for Android to detect and watch for system theme changes. Currently the WebView does not populate the prefers-color-scheme
property with their system dark mode.
npm install capacitor-plugin-color-scheme
npx cap sync
// Set current theme
const result = await ColorScheme.getScheme({ fallbackScheme: 'Dark' });
changeTheme(result.scheme === 'Dark');
// Or, watch for theme changes
ColorScheme.watchScheme((theme: { scheme: DeviceScheme }) => changeTheme(theme === 'Dark'), { fallbackScheme: 'Dark');
// Function to apply theme
function changeTheme(darkMode: boolean) {
const html = document.getElementsByTagName('html')[0];
html.classList.remove('dark', 'light');
html.classList.add(darkMode ? 'dark' : 'light');
}
Ensure that you have uiMode
set in android:configChanges
<?xml version='1.0' encoding='utf-8'?>
<manifest ...>
<application ...>
<activity android:configChanges="uiMode" ...>
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
getScheme(options?: { fallbackScheme?: DeviceScheme | undefined; } | undefined) => Promise<{ scheme: DeviceScheme; }>
Param | Type |
---|---|
options |
{ fallbackScheme?: DeviceScheme; } |
Returns: Promise<{ scheme: DeviceScheme; }>
watchScheme(callback: (result: { scheme: DeviceScheme; }) => any, options?: { fallbackScheme?: DeviceScheme | undefined; } | undefined) => Promise<void>
Param | Type |
---|---|
callback |
(result: { scheme: DeviceScheme; }) => any |
options |
{ fallbackScheme?: DeviceScheme; } |
'Unknown' | 'Light' | 'Dark'