DEV Community

Cover image for Conditionally Appending Developer Tools MenuItem To An Existing Menu In Electron
Abul Hasan Lakhani
Abul Hasan Lakhani

Posted on

Conditionally Appending Developer Tools MenuItem To An Existing Menu In Electron

ElectronJS is one of the most popular JavaScript frameworks these days to write desktop apps using Html, CSS, ReactJS etc. If we look around ourselves, we'll see several apps that are built upon this framework. Visual Studio Code, GitKraken, Discord to name few. You can click here to see the extensive list

Problem/Requirement:

There might be times when you'll need to modify existing ElectronJS menus to add or remove menu items based on some condition. Although the API documentation is really good, there are no examples that show how to mix and match different options.

I am working on a ElectronJs project these days and last night I had to add a menu item conditionally to already existing menu built from template like below:

Menu built from a template:

// Modules to create application menu
const Menu = electron.Menu
const MenuItem = electron.MenuItem

// Template for menu
const menuTemplate = [
  {
    role: 'App',
    submenu: [
      {role: 'close'}
    ]
  },
  {
    label: 'View',
    submenu: [
      {role: 'reload'}
    ]
  },
  {
    id: 'helpMenu',
    role: 'help',
    submenu: [
      {
        label: 'Learn More',
        click: () => {require('electron').shell.openExternal('https://url.com/')}
      }
    ]
  }
]

// Build menu from menuTemplate
const menu = Menu.buildFromTemplate(menuTemplate)

// Set menu to menuTemplate
Menu.setApplicationMenu(menu)

I need Developer Console menu in Development Mode

Most of the examples I've found on the internet show developer tools menu added in the template by default or being added using Api methods but not combination of both. Surely, there might be some way to hide/show or enable/disable the existing menus items but what if we only want to show it when we are in the development. Here is how I did it:


// Other code omitted for brevity

// Build menu from menuTemplate
const menu = Menu.buildFromTemplate(menuTemplate)

if (dev) {
  let menuItem = menu.getMenuItemById('helpMenu')

  menuItem.submenu.append(new MenuItem({
    label: 'Developer Console',
    click: () => {mainWindow.webContents.toggleDevTools()}
  }))
}

// Set menu to menuTemplate
Menu.setApplicationMenu(menu)

// Other code omitted for brevity

That's it! Now when you'll run your Electron app in development mode, you will see Developer Console menu item in the Help menu.

I am still very new to Electron development and there might be better ways or the best way to do it. So please make sure to let me know in the comments or on my twitter @AbulHLakhani. Hope you enjoyed reading it.

Thanks a lot for reading!

P.S This is the my very first blog post on Dev.to so if my writing is not very good, then accept my apologies

Top comments (0)