functioncreateWindow() { // 加载UI代码 const mainWindow = newBrowserWindow({ fullscreen: true, // 全屏窗口 // kiosk: true, // 服务亭模式 // frame: false, // 是否显示窗口边缘框架 // resizable: false, // 不可更改窗口尺寸 // maximizable: true, // 支持最大化 // show: false, // 为了让初始化窗口显示无闪烁,先关闭显示,等待加载完成后再显示。 // width: 800, // height: 600, // ...windowOpenConfig, webPreferences: { // 用于读取本地语音文件 webSecurity: false, // 是否能能在渲染页面中使用node模块 nodeIntegration: true, nodeIntegrationInWorker: true, // contextBridge usage 开启后打开沙盒模式 无法直接通过preload挂在在global上 // contextIsolation: true, preload: path.join(__dirname, 'preload.js'), } }) // 加载html代码 也可以是http链接 可以是个单页应用服务入口url mainWindow.loadFile('./demo.html') // mainWindow.loadURL('http://localhost:3000/demo.html') } // This method will be called when Electron has finished // initialization and is ready to create browser windows. // Some APIs can only be used after this event occurs. app.whenReady().then(() => { createWindow() // 隐藏系统菜单 Menu.setApplicationMenu(null)
app.on('activate', function () { // On macOS it's common to re-create a window in the app when the // dock icon is clicked and there are no other windows open. if (BrowserWindow.getAllWindows().length === 0) createWindow() }) })
// Quit when all windows are closed, except on macOS. There, it's common // for applications and their menu bar to stay active until the user quits // explicitly with Cmd + Q. app.on('window-all-closed', function () { systemLogger.info('主程序关闭') // 手动销毁子进程 经测试子进程内的socket会自动随子进程一起销毁 if (process.platform !== 'darwin') { app.quit() } })
preload.js 负责与渲染进程进行通信
1 2 3 4 5 6 7 8 9 10 11 12 13
/** * The preload script runs before. It has access to web APIs * as well as Electron's renderer process modules and some * polyfilled Node.js functions. * * https://www.electronjs.org/docs/latest/tutorial/sandbox */ const { contextBridge, ipcRenderer } = require('electron')