Today in Impostor Syndrome #12 — How to have an Electron app appear in the tray menu

Thanks to https://github.com/kevinsawicki/tray-example for the Tray example code! In this walkthrough, you’ll see how to get a simple Hello World app to appear in the Menu Tray.

Hello World apps as an umbrella icon in the Menu Tray
  1. Follow the instructions from my previous post on how to create a simple Hello World app. This minimum app is my base for all my future demo apps. (hopefully I’ll be able to continue cranking out simple apps. I have very strong opinions re tech documentation.)
  2. Change your main.js file to the following. We’ll go over the highlights in a second…

Here’s what changed, starting from the top:

  1. First, we require Tray and create a placeholder object.
const {app, BrowserWindow, ipcMain, Tray} = require('electron');
var tray = undefined;

2. The app.on(‘ready’) function is changed to have two functions. The createWindow() does pretty much the same as before, but one key difference: it sets show to false, so the window doesn’t automatically appear.

app.on('ready', function() {
createWindow();
createTray();
});

3. The Tray() constructor must have a valid file. I copied a random umbrella from the tray-example repo.

const createTray = () => {
tray = new Tray(__dirname + ‘/umbrellaTemplate.png’);

4. The toggleWindow(), showWindow(), and getWindowPosition() are self-explanatory.

5. In createWindow(), we see all sorts of fun new parameters to play with, including the show parameter I mentioned earlier. If you set show to true, the window will open in the center of the screen as before (since it isn’t going through showWindow() to grab the location of the Tray icon).

mainWindow = new BrowserWindow({
show: false,
frame: false,

6. the createWindow() also demos how to make the window hide if you click outside.

mainWindow.on(‘blur’, () => {...}

7. You can also have dev tools open by default by adding the following line within the createWindow()

mainWindow.webContents.openDevTools();

and as the blur handler shows, you can also check to see if the dev tools is opened using

if (mainWindow.webContents.isDevToolsOpened()) {...}