一、准备工作

1、使用git下载electron-quick-start.

https://gitee.com/ymyang/electron-quick-start.git

2、使用HBuilder X 导入工程

如图:

Electron 自定义菜单与手动添加菜单_菜单

3、进入electron-quick-start,安装依赖

npm install --save @electron/remote
npm install

二、修改main.js自定义菜单

效果如图:

Electron 自定义菜单与手动添加菜单_javascript_02

1、引入菜单类

const {app,BrowserWindow,Menu,dialog} = require(‘electron’)

2、定义菜单内容

let template = [
  {
	  label: '文件',
	  submenu: [
		  {label: '打开',
			accelerator: 'Ctrl+O',
			click(){
				console.log("open")
			}
		  }
	  ]
  },
  {
  label: '编辑',
  submenu: [{
    label: '撤销',
    accelerator: 'CmdOrCtrl+Z',
    role: 'undo'
  }, {
    label: '重做',
    accelerator: 'Shift+CmdOrCtrl+Z',
    role: 'redo'
  }, {
    type: 'separator'
  }, {
    label: '剪切',
    accelerator: 'CmdOrCtrl+X',
    role: 'cut'
  }, {
    label: '复制',
    accelerator: 'CmdOrCtrl+C',
    role: 'copy'
  }, {
    label: '粘贴',
    accelerator: 'CmdOrCtrl+V',
    role: 'paste'
  }, {
    label: '全选',
    accelerator: 'CmdOrCtrl+A',
    role: 'selectall'
  }]
}, {
  label: '查看',
  submenu: [{
    label: '重载',
    accelerator: 'CmdOrCtrl+R',
    click: function (item, focusedWindow) {
      if (focusedWindow) {
        // 重载之后, 刷新并关闭所有的次要窗体
        if (focusedWindow.id === 1) {
          BrowserWindow.getAllWindows().forEach(function (win) {
            if (win.id > 1) {
              win.close()
            }
          })
        }
        focusedWindow.reload()
      }
    }
  }, {
    label: '切换全屏',
    accelerator: (function () {
      if (process.platform === 'darwin') {
        return 'Ctrl+Command+F'
      } else {
        return 'F11'
      }
    })(),
    click: function (item, focusedWindow) {
      if (focusedWindow) {
        focusedWindow.setFullScreen(!focusedWindow.isFullScreen())
      }
    }
  }, {
    label: '切换开发者工具',
    accelerator: (function () {
      if (process.platform === 'darwin') {
        return 'Alt+Command+I'
      } else {
        return 'Ctrl+Shift+I'
      }
    })(),
    click: function (item, focusedWindow) {
      if (focusedWindow) {
        focusedWindow.toggleDevTools()
      }
    }
  }, {
    type: 'separator'
  }, {
    label: '应用程序菜单演示',
    click: function (item, focusedWindow) {
      if (focusedWindow) {
        const options = {
          type: 'info',
          title: '应用程序菜单演示',
          buttons: ['好的'],
          message: '此演示用于 "菜单" 部分, 展示如何在应用程序菜单中创建可点击的菜单项.'
        }
        dialog.showMessageBox(focusedWindow, options, function () {})
      }
    }
  }]
}, {
  label: '窗口',
  role: 'window',
  submenu: [{
    label: '最小化',
    accelerator: 'CmdOrCtrl+M',
    role: 'minimize'
  }, {
    label: '关闭',
    accelerator: 'CmdOrCtrl+W',
    role: 'close'
  }, {
    type: 'separator'
  }, {
    label: '重新打开窗口',
    accelerator: 'CmdOrCtrl+Shift+T',
    enabled: false,
    key: 'reopenMenuItem',
    click: function () {
      app.emit('activate')
    }
  }]
}, {
  label: '帮助',
  role: 'help',
  submenu: [{
    label: '学习更多',
    click: function () {
      shell.openExternal('http://electron.atom.io')
    }
  }]
}]

3、创建窗口,构件菜单

function createWindow() {
	/* 创建一个浏览器窗口。*/
	const mainWindow = new BrowserWindow({		
		width: 800,
		height: 600,
		show: false,		
		icon: './static/image/favicon.ico',
		title: '酷猪收银',
		webPreferences: { //允许使用require			
			nodeIntegration: true,
			contextIsolation: false,
			enableRemoteModule: true, // 启用remote模块
		}
	})
	require('@electron/remote/main').initialize()
    require("@electron/remote/main").enable(mainWindow.webContents)
	/* 将index.html加载进一个新的BrowserWindow实例。*/
	mainWindow.loadFile('index.html')

	mainWindow.on("ready-to-show", () => {
		mainWindow.show()
	})

	/* 拼接路径比单文件名更好 */
	/* mainWindow.loadFile(path.join(__dirname, 'index.html')) */

	/* 打开开发工具。*/
	// mainWindow.webContents.openDevTools()

	mainWindow.on('close', () => {
		console.log("当前窗口关闭时.....")
		mainWindow = null
	})

	mainWindow.webContents.on('did-finish-load', function() {
		console.log("导航完成.....")
	})
	
	const menu = Menu.buildFromTemplate(template)
	Menu.setApplicationMenu(menu)
}
app.whenReady().then(() => {
	createWindow()

	app.on('activate', function() {
		/* activate事件是专为 macOS 系统定制的事件 */
		/* 在 macOS 系统中 */
		/* 没有其他窗口打开时单击dock图标,通常会在应用程序中重新创建一个窗口。*/
		if (BrowserWindow.getAllWindows().length === 0) createWindow()
	})
})

三、手动添加菜单

1、修改index.html页,添加如下内容

<div class="menu-box">
		<button id="addMenu">创建菜单</button>
		<br/>
		<input type="text" placeholder="输入自定义菜单项内容" id="menuText"/>
		<button id="addItem">添加菜单项</button>
	</div>

2、创建menu.js,并引入

<script src="./menu.js"></script>

3、在menu.js中实现

const remote = require("@electron/remote")
const Menu = remote.Menu
const MenuItem = remote.MenuItem

let mainWin = remote.getCurrentWindow()

window.addEventListener('DOMContentLoaded',() => {
	const addMenu = document.getElementById('addMenu')
	const menuText = document.getElementById('menuText')
	const addItem = document.getElementById('addItem')
	
	let menuItem = new Menu()
	//添加主菜单
	addMenu.addEventListener('click', () => { 
		let menuSelect = new MenuItem({label:'选择', type: 'normal'})
		let menuRun = new MenuItem({label:'运行', type: 'normal'})
		
		let customMenu = new MenuItem({label:'自定义菜单', submenu: munuItem})
		
		let menu = new Menu()
		menu.append(menuSelect)
		menu.append(menuRun)
		menu.append(customMenu)
		Menu.setApplicationMenu(menu)
	})
	//添加子菜单
	addItem.addEventListener('click', () => {
		let txt = menuText.value.trim()
		if(txt){
			menuItem.append(new MenuItem({label: txt, type: 'normal'}))
			menuText.value = ''
		}
	})
})