tray
module allows you to create an icon in the
operating system's notification area.
This icon can also have a context menu attached.
Open the full API documentation (opens in new window) in your browser.
The demo button sends a message to the main process using the
ipc
module. In the main process the app is told to
place an icon, with a context menu, in the tray.
In this example the tray icon can be removed by clicking 'Remove' in the context menu or selecting the demo button again.
const path = require('path')
const {ipcMain, app, Menu, Tray} = require('electron')
let appIcon = null
ipcMain.on('put-in-tray', (event) => {
const iconName = process.platform === 'win32' ? 'windows-icon.png' : 'iconTemplate.png'
const iconPath = path.join(__dirname, iconName)
appIcon = new Tray(iconPath)
const contextMenu = Menu.buildFromTemplate([{
label: 'Remove',
click: () => {
event.sender.send('tray-removed')
}
}])
appIcon.setToolTip('Electron Demo in the tray.')
appIcon.setContextMenu(contextMenu)
})
ipcMain.on('remove-tray', () => {
appIcon.destroy()
})
app.on('window-all-closed', () => {
if (appIcon) appIcon.destroy()
})
const ipc = require('electron').ipcRenderer
const trayBtn = document.getElementById('put-in-tray')
let trayOn = false
trayBtn.addEventListener('click', function (event) {
if (trayOn) {
trayOn = false
document.getElementById('tray-countdown').innerHTML = ''
ipc.send('remove-tray')
} else {
trayOn = true
const message = 'Click demo again to remove.'
document.getElementById('tray-countdown').innerHTML = message
ipc.send('put-in-tray')
}
})
// Tray removed from context menu on icon
ipc.on('tray-removed', function () {
ipc.send('remove-tray')
trayOn = false
document.getElementById('tray-countdown').innerHTML = ''
})
On Linux distributions that only have app indicator support, users
will need to install libappindicator1
to make the
tray icon work. See the
full API documentation (opens in new window)
for more details about using Tray on Linux.