Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”

This article has participated in the “Digitalstar Project” and won a creative gift package to challenge the creative incentive money.

The sample code

One, custom menu

In three steps

  1. Defining menu contents
let menuTemp = [{
	label: 'File'.click(){}}]Copy the code

Each item in the array is a menuItem

  1. Generate a menu from the above template data
const menu = Menu.buildFromTemplate(menuTemp)
Copy the code
  1. Add the above custom menu to the app
Menu.setApplicationMenu(menu)
Copy the code

Example:

// In main process main.js
let menuTemp = [
	{
		label: 'File'.submenu: [{label: 'New File'.click() {
					shell.openExternal('https://kaiwu.lagou.com/')}}, {label: 'Preferences'.click() {
					BrowserWindow.getFocusedWindow().webContents.send('preferences')}}, {type: 'separator'
			},
			{
				label: 'open File'
			},
			{
				label: 'about'.role: 'about'}]}, {label: 'Edit'
	},
	{
		label: The 'role'.submenu: [{label: 'copy'.role: 'copy' },
			{
				label: 'cut'.role: 'cute'
			},
			{
				label: 'paste'.role: 'paste'
			},
			{
				label: Minimize.role: 'minimize'
			},
			{
				label: 'zoom in'.role: 'zoomin'}]}, {label: 'Four types'.submenu: [{label: 'option 1'.type: 'checkbox' },
			{ label: 'option 2'.type: 'checkbox' },
			{ label: 'option 3'.type: 'checkbox' },
			{ type: 'separator' },
			{
				label: 'item1'.type: 'radio'
			},
			{
				label: 'item2'.type: 'radio'
			},
			{
				label: 'Windows'.type: 'submenu'.role: 'windowMenu'}]}, {label: 'other'.submenu: [{label: 'open'.icon: './file.ico'.accelerator: 'Ctrl + o'.click() {
					BrowserWindow.getFocusedWindow().webContents.send(
						'mtp'.'Main process sends message to renderer'}}]}]// 2. Generate a menu based on the above template data
const menu = Menu.buildFromTemplate(menuTemp)
// 3. Add the above custom menu to the app
Menu.setApplicationMenu(menu)
Copy the code

The command output is as follows:

2. Create a menu dynamically

The steps are as follows

  1. Instantiate Menu
let menu = new Menu()
Copy the code
  1. Instantiate a menuItem
let menuFile = new MenuItem({ label: 'file'.type: 'normal' })
Copy the code
  1. Add the created custom menu to Menu
menu.append(menuFile)
Copy the code
  1. Set menu menu
Menu.setApplicationMenu(menu)
Copy the code

Example:

<! DOCTYPE html><html lang="en">
	<body>
		<h2>Custom menu</h2>
		<button id="addMenu">Create a custom menu</button>
		<br />
		<br />
		<input type="text" placeholder="Enter custom menu item contents" id="menuCon" />
		<br />
		<br />
		<button id="addItem">Add menu items</button>
		<script src="./index3.js"></script>
	</body>
</html>
Copy the code
const { Menu, MenuItem } = require('@electron/remote')

window.addEventListener('DOMContentLoaded'.() = > {
	let addMenu = document.getElementById('addMenu')
	let menuCon = document.getElementById('menuCon')
	let addItem = document.getElementById('addItem')

	let menuItem = new Menu()
	// Generate a menu
	addMenu.addEventListener('click'.() = > {
		let menuFile = new MenuItem({ label: 'file'.type: 'normal' })
		let menuEdit = new MenuItem({ label: 'edit'.type: 'normal' })
		let customMenu = new MenuItem({ label: 'Custom menu Item'.submenu: menuItem })

		// Add the created custom menu to menu
		let menu = new Menu()
		menu.append(menuFile)
		menu.append(menuEdit)
		menu.append(customMenu)

		Menu.setApplicationMenu(menu)
	})
	addItem.addEventListener('click'.() = > {
		const value = menuCon.value.trim()
		if (value) {
			menuItem.append(new MenuItem({ label: value, type: 'normal' }))
			menuCon.value = ' '}})})Copy the code

See index3 in the example

Three, right menu

The first two steps are the same as the custom menu

  1. Defining menu contents
let contextTemp = [
    { label: 'Run Code' },
    { label: 'Go to defination' },
    {
        type: 'separator'
    },
    {
        label: 'Other features'.click() {
            console.info('Other options have been clicked.')}}]Copy the code
  1. Generate a menu from the above template data
let menu = Menu.buildFromTemplate(contextTemp)
Copy the code
  1. Listen for the contextMenu event and use the menu.popup function
window.addEventListener(
    'contextmenu'.(ev) = > {
         ev.preventDefault()
         menu.popup({ window: getCurrentWindow() })
     },
     false
)
Copy the code

menu.popup([browserWindow, x, y, positioningItem])

  • browserWindowBrowserWindow (optional) – Defaultnull.
  • xNumber (Optional) – The default value is -1.
  • y Number (Must beIf x is set) – Default is -1.
  • positioningItemNumber (optional)OS X– Index of the menu item below the specified mouse position at the specified coordinates. The default is 1.

Bring up the Context Menu in browserWindow. You can optionally provide specified X, y to set where the menu should be placed, otherwise it will default to the current mouse position.

Example:

const { Menu, getCurrentWindow } = require('@electron/remote')

let contextTemp = [
	{ label: 'Run Code' },
	{ label: 'Go to defination' },
	{
		type: 'separator'
	},
	{
		label: 'Other features'.click() {
			console.info('Other options have been clicked.')}}]let menu = Menu.buildFromTemplate(contextTemp)
window.addEventListener('DOMContentLoaded'.() = > {
	window.addEventListener(
		'contextmenu'.(ev) = > {
			ev.preventDefault()
			menu.popup({ window: getCurrentWindow() })
		},
		false)})Copy the code

See Index4 in the example