[英]Dark mode detection in Node/Electron
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.
我想要做的是,当系统处于“暗模式”时,我希望 CSS 标签发生变化。 For instance, when a user has Dark Mode turned on in the system, it'll change the css background color to black.
例如,当用户在系统中打开暗模式时,它会将 css 背景颜色更改为黑色。
here's the HTML code:这是 HTML 代码:
<nav class="navbar navbar-light bg-light">
Here's the javascript in the renderer.js
file I used from this site with jQuery.这是我在本网站上使用 jQuery 使用的
renderer.js
文件中的 javascript。 I also had to use the console.log
module to test to make sure the trigger works.我还必须使用
console.log
模块进行测试以确保触发器正常工作。
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.我知道 Electron/Node.js 中必须有不同的
window.NAMEOFTHING
。 I guess there's another npm I should try?我想我应该尝试另一个 npm 吗?
You can check if system is in dark mode or not using the nativeTheme
module.您可以使用
nativeTheme
模块检查系统是否处于暗模式。
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.然而,这似乎只适用于编译的应用程序,所以当我运行
npm start
它不起作用。 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.它将返回未定义,因此对于开发,您可能想要一个单独的 function 来检查其是否未定义并默认为暗模式或亮模式。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.