main.js 文件
// 模块来控制应用程序的生命周期并创建本地浏览器窗口
const { app, BrowserWindow, ipcMain, nativeTheme } = require('electron')
const path = require('path')
// 定义一个窗口对象
var mainWindow = null;
app.on("ready", ()=>{
// 创建浏览器窗口
mainWindow = new BrowserWindow({
width: 800,
height: 600,
webPreferences: {
nodeIntegration:true,
preload: path.join(__dirname, 'preload.js')
}
})
//然后加载应用的index.html。
mainWindow.loadFile('index.html');
//暗黑主题设置
ipcMain.handle('dark-mode:toggle', () => {
if (nativeTheme.shouldUseDarkColors) {
nativeTheme.themeSource = 'light'
} else {
nativeTheme.themeSource = 'dark'
}
return nativeTheme.shouldUseDarkColors
})
//打开独立的浏览器调试窗口
// mainWindow.webContents.openDevTools({mode:'detach'})
// 当窗口关闭时处理掉窗口对象
mainWindow.on('closed', ()=>{
mainWindow = null
})
});
preload.js 文件
const { contextBridge, ipcRenderer } = require('electron')
contextBridge.exposeInMainWorld('darkMode', {
toggle: () => ipcRenderer.invoke('dark-mode:toggle'),
system: () => ipcRenderer.invoke('dark-mode:system')
})
index.html 文件
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Hello World!</title>
<meta http-equiv="Content-Security-Policy" content="script-src 'self' 'unsafe-inline';" />
<link rel="stylesheet" type="text/css" href="./styles.css">
</head>
<body>
<h1>Hello World!</h1>
<p>Current theme source: <strong id="theme-source">System</strong></p>
<button id="toggle-dark-mode">Toggle Dark Mode</button>
<script>
//更换主题事件
document.getElementById('toggle-dark-mode').addEventListener('click', () => {
window.darkMode.toggle()
})
</script>
</body>
</body>
</html>
调用 window.darkMode.toggle() 更换主题
window.darkMode.toggle()
示例:
因篇幅问题不能全部显示,请点此查看更多更全内容