electron版本:v18.1.0
一、主进程引入Menu模块
const { Menu } = require('electron')
二、编写菜单数据并启用
const { Menu, BrowserWindow } = require('electron') var template = [ { label: '菜单A',//一级菜单名称 submenu: [ //定义子菜单 { label: '打开新窗口', accelerator: 'ctrl+n',//添加快捷键 click: () => { //添加点击事件 var win = new BrowserWindow({ width: 500, height: 500, webPreFerences: { nodeIntegration: true } }) win.loadFile("newWindow.html") win.on("closed", () => { win = null }); } }, { label: '菜单A2' } ] }, { label: '菜单B', submenu: [ { label: '菜单B1' }, { label: '菜单B2' } ] } ] var m = Menu.buildFromTemplate(template) Menu.setApplicationMenu(m)
三、完整代码
inex.js
var electron = require('electron') //引入electron组件 var app = electron.app //引入组件app var BrowserWindow = electron.BrowserWindow //窗口引用 var mainWindow = null //申明打开窗口 app.on('ready', () => { //app初始化参数 mainWindow = new BrowserWindow({ windth: 800, height: 800, webPreferences: { nodeIntegration: true, contextIsolation: false, enableRemoteModule: true } }) require('./main/menu.js') mainWindow.webContents.openDevTools() //默认打开调试模式 mainWindow.loadFile('index.html') //打开窗口加载的页面 mainWindow.on('close', () => { //窗口关闭时,释放页面 mainWindow = null }) })
index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>menu</title> </head> <body> menu </body> </html>
menu.js
const { Menu, BrowserWindow } = require('electron') var template = [ { label: '菜单A',//一级菜单名称 submenu: [ //定义子菜单 { label: '打开新窗口', accelerator: 'ctrl+n',//添加快捷键 click: () => { //添加点击事件 var win = new BrowserWindow({ width: 500, height: 500, webPreFerences: { nodeIntegration: true } }) win.loadFile("newWindow.html") win.on("closed", () => { win = null }); } }, { label: '菜单A2' } ] }, { label: '菜单B', submenu: [ { label: '菜单B1' }, { label: '菜单B2' } ] } ] var m = Menu.buildFromTemplate(template) Menu.setApplicationMenu(m)
newWindow.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>菜单打开新窗口</title> </head> <body> 菜单打开新窗口 </body> </html>
四、运行效果
electron .