main.js
import { app, BrowserWindow, ipcMain, nativeTheme } from "electron"
//nativeTheme.themeSource = 'dark' //设置为深色主题
//切换主题
ipcMain.handle("toggleTheme", () => {
if (nativeTheme.shouldUseDarkColors) { //如果系统为深色主题时
nativeTheme.themeSource = 'light' //设置为浅色主题
return "浅色主题"
} else {
nativeTheme.themeSource = 'dark' //设置为深色主题
return "深色主题"
}
})
preload.mjs
contextBridge.exposeInMainWorld('DRAPI',{
toggleTheme: () => { //切换主题
return ipcRenderer.invoke('toggleTheme')
}
})
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'">
<title>邓瑞编程</title>
<link rel="stylesheet" href="../css/base.css">
</head>
<body>
dengruicode.com <hr>
<button id="toggleTheme">切换主题</button>
<script src="../js/index.js"></script>
</body>
</html>
index.js
//切换主题
document.querySelector('#toggleTheme').addEventListener('click', async () => {
let theme = await DRAPI.toggleTheme()
console.log(theme)
})
base.css
/* 深色主题 */
@media (prefers-color-scheme: dark) {
a {
color: #fff;
}
body {
color: #fff;
background: #272727;
}
}
7.设置主题
-- 未经授权禁止转载 --