I read on the electron's guide to implement dark mode to your app, but it only works when the user clicks a button to manually change it to dark mode. What I want to do is, when the system is in 'dark mode', I wanted the CSS tag to change. For instance, when a user has Dark Mode turned on in the system, it'll change the css background color to black.
here's the HTML code:
<nav class="navbar navbar-light bg-light">
Here's the javascript in the renderer.js
file I used from this site with jQuery. I also had to use the console.log
module to test to make sure the trigger works.
window.matchMedia('(prefers-color-scheme: dark)')
.addEventListener('change', event => {
if (event.matches) {
//dark mode
$("nav.navbar-light bg-light").replaceWith( "navbar-light bg-dark" );
console.log("This is Dark Mode");
} else {
//light mode
$("nav.navbar-light bg-light").replaceWith( "navbar-light bg-light" );
console.log("This is Light Mode");
}
})
I tried those, and nothing showed up on my console on launch. I know there has to be a different window.NAMEOFTHING
in Electron/Node.js. I guess there's another npm I should try?
You can check if system is in dark mode or not using the nativeTheme
module.
So add this to your code:
const electron = require("electron")
const nativeTheme = electron.remote.nativeTheme
if (nativeTheme.shouldUseDarkColors) {
// Code here
}
However this only seems to work in compiled apps, so when I run npm start
it does not work. It will return undefined, so for development you might wanna have a seperate function which checks if its undefined and defaults to dark or light mode.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.