为了将 Electron 的 nativeTheme 传递到前端,可以使用 IPC(进程间通信)来实现。具体步骤如下:

  1. 在 Electron 的主进程中,定义一个函数来获取 nativeTheme,并使用 ipcMain 发送给渲染进程:
const { ipcMain, nativeTheme } = require('electron');

// 获取 nativeTheme
function getNativeTheme() { 
  return nativeTheme.shouldUseDarkColors ? 'dark' : 'light';
}

// 监听渲染进程请求获取 nativeTheme
icpMain.on('getNativeTheme', (event) => {
  event.returnValue = getNativeTheme();
});
  1. 在渲染进程中,使用 ipcRenderer 发送请求获取 nativeTheme:
const { ipcRenderer } = require('electron');

// 发送获取 nativeTheme 的请求
const nativeTheme = ipcRenderer.sendSync('getNativeTheme');
console.log('nativeTheme: ' + nativeTheme);

注意:在使用 IPC 传递数据时,需要确保主进程和渲染进程都已经初始化完成。可以在主进程中使用 app 的 ready 事件和在渲染进程中使用 DOMContentLoaded 事件来确保两者都已经初始化完成。


原文地址: https://www.cveoy.top/t/topic/odfc 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录