Home »
Electron JS
How to add tray icon menu in Electron JS?
Electron JS | Add Tray Icon Menu: In this article, we will learn how to add a tray icon menu in an Electron JS Application?
Submitted by Godwill Tetah, on June 15, 2020
If you are new here, please consider checking out my recent articles on Electron JS including Tray Icons.
In this tutorial, we will set up 2 menu items for a tray icon which when a user right-clicks, the menu appears just like the image below.
Adding a menu to a system tray icon is the functionality of a tray method known as the tray.setContextMenu(), where the parameter is simply a variable or constant of the menu items passed in Menu.buildFromTemplates([]).
In this exercise,
- I will create a tray icon first,
- Create a constant which holds the menu items in an array,
- And finally, pass it as a parameter to the tray method setContextMenu().
We are also going to use the path module which is a Node.Js built-in module to locate the source of our tray icon image and the menu module where the method Menu.buildFromTemplates([]) is derived from.
Finally, let us write some code: Open your main JavaScript file and type,
//system tray icon menu//
const electron = require ('electron') // imports electron
const path = require ('path') // imports path module
const {app, Menu, Tray} = electron // imports menu and tray modules
const BrowserWindow = electron.BrowserWindow //enables UI
let mainWindow;
let tray
app.on('ready', _ => {
tray = new Tray (path.join ('src', 'Tray.PNG' ) ) // sets tray icon image
const contextMenu = Menu.buildFromTemplate([ // define menu items
{
label: 'Help',
click: () => console.log ('Help') // click event
},
{
label: 'System',
click: () => console.log ('System')
}
])
tray.setContextMenu(contextMenu)
mainWindow = new BrowserWindow({ // sets browser window dimensions
height : 600,
width : 600,
})
})
Finally, run your code and enjoy the output.
Output:
Hey! The browser window displays too... I just did not take a screenshot because it is blank.
Thanks for reading.
Drop your comments if in need of help.