Skip to content
Tutorials Center
My learning

Topics

Lesson 18 of 36 ยท Windows, Menus and Tray

Tray Icons, Notifications and Run-in-Background Apps

Add a system tray icon with a menu, hide the window to the tray instead of quitting, show native notifications, badges and taskbar progress in Electron, with runnable state models.

Some apps are not meant to live in a window all day. A chat client, a download manager, a clipboard tool or a music player wants to keep running in the background, show a small icon near the clock, and speak up only when something needs attention. Electron supports this with the tray, notifications and a few taskbar and dock features.

The tray icon

The Tray class adds an icon to the system tray (Windows notification area), menu bar (macOS) or status area (Linux). It lives in the main process.

JavaScript
const { app, Tray, Menu, nativeImage, BrowserWindow } = require('electron')
const path = require('node:path')

let tray = null          // keep a reference, or the icon can disappear when garbage collected
let win = null

app.whenReady().then(() => {
  win = new BrowserWindow({ width: 420, height: 560 })
  win.loadFile('index.html')

  const icon = nativeImage.createFromPath(path.join(__dirname, '../../assets/tray.png'))
  tray = new Tray(icon.resize({ width: 16, height: 16 }))
  tray.setToolTip('My App')

  const menu = Menu.buildFromTemplate([
    { label: 'Show window', click: () => { win.show(); win.focus() } },
    { label: 'Pause syncing', type: 'checkbox', click: (item) => setSyncPaused(item.checked) },
    { type: 'separator' },
    { label: 'Quit', click: () => app.quit() },
  ])
  tray.setContextMenu(menu)

  tray.on('click', () => (win.isVisible() ? win.hide() : win.show()))   // Windows and Linux
})

Icon tips:

  • Use PNG (or .ico on Windows) at 16x16 and 32x32 (the @2x suffix, like [email protected], supplies the retina version automatically).
  • On macOS, use a template image: a black-and-transparent PNG whose file name ends in Template (such as trayTemplate.png). macOS recolors it for light and dark menu bars.
  • Keep the Tray object in a module-level variable. A tray created in a function and not stored is garbage collected, and the icon vanishes.

You can also update the icon and tooltip at runtime (tray.setImage, tray.setToolTip), for example to show an "unread" state. On macOS, tray.setTitle('3') places text next to the icon.

Hide to tray instead of quitting

A tray app should keep running when the user closes the window. Intercept the window's close event, hide the window, and only quit when the user chooses Quit. The subtle part is telling "close the window" from "quit the app", for which a flag is set in before-quit.

JavaScript
let isQuitting = false

app.on('before-quit', () => { isQuitting = true })

win.on('close', (event) => {
  if (!isQuitting) {
    event.preventDefault()
    win.hide()
    if (process.platform === 'darwin') app.dock.hide()
  }
})

Do not also call app.quit() in window-all-closed for tray apps, since hiding a window does not close it. Let the user know how to quit: without a hint, people think the app is gone.

Here is the same logic as a runnable state machine. It processes a sequence of user actions and prints what the window and the app do, so you can verify there is no way to get stuck.

Node.js Stand-in: hide to tray state machine

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Notifications

Electron offers the Notification class in the main process (and the standard web Notification API in renderers, which Electron routes to native notifications as well). The main-process version gives more control and works even when no window is open.

JavaScript
const { Notification } = require('electron')

if (Notification.isSupported()) {
  const n = new Notification({
    title: 'Download finished',
    body: 'report.pdf is ready.',
    silent: false,
    urgency: 'normal',              // Linux
    actions: [{ type: 'button', text: 'Open' }],   // macOS
  })
  n.on('click', () => { win.show(); win.focus() })
  n.on('action', (event, index) => console.log('button', index))
  n.show()
}

Notification guidelines that make users happy:

  • Notify only about things that matter when the user is not looking at your app. Check win.isFocused().
  • Make the click do something useful, such as showing the relevant window.
  • Group or throttle: ten download notifications at once is spam.
  • On Windows, notifications need an AppUserModelID: call app.setAppUserModelId('com.example.myapp') early (packaging tools set it too), or notifications may not appear or show the wrong name.
  • Respect OS "Do Not Disturb" settings; Electron cannot override them, which is how it should be.

The notification policy is plain logic and worth testing on its own. The stand-in below decides whether to notify, merges bursts into one summary, and tags what clicking does:

Node.js Stand-in: notification policy with batching

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Badges, progress and attention

Small signals on the taskbar or dock icon keep users informed without popups:

JavaScript
app.setBadgeCount(3)                  // macOS dock, some Linux launchers
win.setOverlayIcon(img, '3 unread')   // Windows taskbar overlay
win.setProgressBar(0.4)               // 0 to 1; -1 removes it; 2 means indeterminate on Windows
win.flashFrame(true)                  // flash the taskbar button until the window is focused
app.dock?.bounce('informational')     // macOS

These calls are cheap, so update them whenever your unread count or progress changes, and reset them (setProgressBar(-1)) when the task ends.

Platform notes

  • Linux tray support varies by desktop environment; some require an appindicator extension. Do not make the tray the only way to quit or reach a feature.
  • macOS menu bar items are narrow; use template images and short titles.
  • Windows may hide new tray icons in the overflow area until the user pins them; you cannot force that.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why must you keep the Tray object in a long-lived variable?

    A Tray that is only referenced inside a function can be garbage collected, removing the icon.
  2. 2. How does a tray app tell 'close the window' from 'quit the app'?

    A before-quit flag lets the close handler preventDefault and hide the window only when the user did not choose Quit.
  3. 3. What does a macOS template image give you?

    A black-and-transparent image named with the Template suffix is tinted by macOS to match the menu bar.
  4. 4. On Windows, what is needed for notifications to show reliably?

    Windows ties notifications to an AppUserModelID, which packaging usually sets but which you can set explicitly.
  5. 5. When is it good practice to skip a notification?

    Notifications are for attracting attention when the user is elsewhere; in-app UI is better when they are looking at the app.

Summary

  • Tray adds a system tray icon with a context menu and click handler; keep the reference alive.
  • Tray apps hide the window on close and quit only through an explicit action (use a before-quit flag).
  • Notification shows native notifications; notify sparingly, batch bursts and make clicks useful.
  • Use badges, taskbar progress and flashFrame for lightweight signals, and never make the tray the only way to reach a feature.

Next: Native Dialogs and Working with Files