Adding a menu bar to the application

You must have a menu bar for a desktop application. As we are dealing with HTML and CSS, it's easy to create a menu based on HTML and CSS. However, here, in order to understand Electron's ability to use the native operating system components, let's create it the Electron way. This uses a native operating system component.

Electron provides two classes to create menus: Menu and MenuItem. Each menu consists of multiple menu items and each menu item can have a sub menu. The menu class is only available in the main process. So, this will be rendered along with your Electron window.

Open the main.js file inside src folder and update the code as shown in the following:

const { app, BrowserWindow, Menu } = require('electron'); 

const template = [{
label: 'File',
submenu: [
{
// similar to role: 'reload'. The code is just for demo
// purpose. For reloading the window content in menu used
// the role reload.
label: 'Reload',
accelerator: 'CmdOrCtrl+R',
click (item, focusedWindow) {
if (focusedWindow)
focusedWindow.reload()
},
},
{
// This section can be replaced with role: toggledevtools
//as there is a role available to do the same.
label: 'Toggle Developer Tools',
accelerator: process.platform === 'darwin' ?
'Alt+Command+I' : 'Ctrl+Shift+I'
click (item, focusedWindow) {
if (focusedWindow)
focusedWindow.webContents.toggleDevTools()
}
},
{
type: 'separator'
},
{
role: 'resetzoom'
},
{
role: 'zoomin'
}
]
}];

function createWindow() {
//...
// Initializes the Menubar from the template
const menu = Menu.buildFromTemplate(template);
Menu.setApplicationMenu(menu);
}

Each item in the template array serves as the constructor parameter for the MenuItem class.role string. Define the action of the menu item; when specified the click property will be ignored. You can attach an event handler to the menu item by specifying the click function explicitly. The Type option can be used to specify the type of menu item: possible values are normal, separator, submenu, checkbox, or radio.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.218.93.169