Create your account

Already have an account? Login here

Note: By joining, you will receive periodic emails from Coursetro. You can unsubscribe from these emails.

Create account

Working with Electron Menus - Tutorial

By Gary simon - Nov 28, 2017

This tutorial is based on our 100% free courseCreating Desktop Apps with Electron Tutorial

In the previous lesson, we installed a brand new Electron project and got it all setup. In this lesson, we're going to take a look at how to integrate a custom menu for our app.

In case you haven't followed along, we're building an app that will notify the user through native desktop notifications, when the price of 1 Bitcoin (BTC) exceeds a user-specified threshold.

Let's get started!

If you prefer watching a video..

Be sure to Subscribe to the Official Coursetro Youtube Channel for more videos.

..video coming soon..

Integrating a Custom Menu

In order to create a custom menu for our Electron app, we have to first import Menu from electron in at the top of our main.js file:

// From
const {app, BrowserWindow} = require('electron')

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

Next, near the bottom of our createWindow() function, we add:

function createWindow () {

  // Other code removed for brevity

  var menu = Menu.buildFromTemplate([
      {
          label: 'Menu',
          submenu: [
              {label:'Adjust Notification Value'},
              {label:'CoinMarketCap'},
              {label:'Exit'}
          ]
      }
  ])
  Menu.setApplicationMenu(menu); 

}

First, we reference Menu.buildFromTemplate([{}]), which is where our menu is actually defined and built, within a series of arrays and objects.

The label property defines the name that shows up in the actual menu of our app.

The submenu property is an array of objects, with each object defining the actual menu items displayed when the label is clicked.

Finally, use .setApplicationMenu to set the menu. If you save the project, and run npm start in the console, you will see:

But if you click on them, nothing happens. Let's fix that.

Making the Menu Items Clickable

Going back to our main.js, add the following code to make our Exit button close the application:

  var menu = Menu.buildFromTemplate([
    {
        label: 'Menu',
            submenu: [
            {label:'Adjust Notification Value'},
            {label:'CoinMarketCap'},
            {
                label:'Exit', 
                click() { 
                    app.quit() 
                } 
            }
        ]
    }
  ])

So, to make a menu item clickable, we simply add a comma after the label value, and reference click() { }.

In this case, we're calling app.quit() when the Exit submenu item is clicked. Give it a try by running npm start in the console and click Exit.

While we're here, let's also make our CoinMarketCap item launch a browser window with the CoinMarketCap website on click.

To open a browser window, we first have to import the Electron shell at the top:

// Other variables removed for brevity

const shell = require('electron').shell

Then, we modify our menu as such:

            {label:'Adjust Notification Value'},
            {
                label:'CoinMarketCap',
                click() { 
                    shell.openExternal('http://coinmarketcap.com')
                } 
            },
            {
                label:'Exit', 
                click() { 
                    app.quit() 
                } 
            }

Great! Give it a go by re-running npm start.

Separating Menu Items

Sometimes, it makes sense to separate your submenu items based on priority. For instance, let's create a line that separates the Exit button from the two submenu items above it:

            {
                label:'CoinMarketCap',
                click() { 
                    shell.openExternal('http://coinmarketcap.com')
                } 
            },
            {type:'separator'},  // Add this
            {
                label:'Exit', 
                click() { 
                    app.quit() 
                } 
            }

Easy! We just add an object with a property of type and a value of separator.

The result should look like this:

Creating Keyboard Shortcuts for Menu Items

Let's say for instance, that we want to allow the user to launch the CoinMarketCap website by hitting a keyboard shortcut. In other words, how can we define a keyboard shortcut to simulate a click event on a submenu item?

Easy! Adjust the code as follows:

            {
                label:'CoinMarketCap',
                click() { 
                    shell.openExternal('http://coinmarketcap.com')
                },
                accelerator: 'CmdOrCtrl+Shift+C'
            },

We simply add the accelerator property and define the keyboard shortcut. You can view all of the available keyboard shortcuts, codes and modifiers here.

If you restart the application, it will now work if you try the keyboard shortcut. It will also inform the user in the actual submenu item, as shown below:

Defining Multiple Menu Labels

While our particular app is only going to have 1 menu label, I definitely want to show you how you can create more, which is rather simple if you understand objects.

You can create a second one by simply creating a second object in the array, as shown below:

  var menu = Menu.buildFromTemplate([
    {
        label: 'Menu',
        // Other code removed for brevity
    },
    {
        label: 'Info'
    }
  ])

Save it, and you will find the second label in the menu:

Conclusion

Going forward, we will make our very first submenu item function later on "Adjust Notification Value". But for now, we're going to conclude this lesson and in the next lesson, take a look at creating other windows in Electron.

This tutorial is based on our 100% free courseCreating Desktop Apps with Electron Tutorial


Share this post




Say something about this awesome post!