Dealing with tray icons

Electron has a built-in class called Tray, that can be used to add custom icon and menu to the notification area. Each platform is having different look and feels for this tray icon. However, this is quite useful to attach some quick action to the application. For instance, the tray icon on macOS should look as shown the following screenshot:

In Linux and Windows, it looks different. However, the same Tray class can be used to create tray icon for all major platforms. Creating a tray icon is simple with the Tray class. The class should be instantiated after the app module emits the ready event. The following code creates a tray icon and adds some quick menu items into the tray icon context menu:

const { app, BrowserWindow, Tray, Menu } = require('electron');

let appShell;
let tray;

app.on('ready', () => {
appShell = new BrowserWindow({ width: 800, height: 600 });
appShell.loadURL(appUrl);
appShell.on('closed', () => { appShell = null; });
tray = new Tray('/Users/Guest/Workspace/icon.png');
const contextMenu = Menu.buildFromTemplate([
{
label: 'Show window',
click: function () {
appShell.show();
}
},
{
label: 'Hide Window',
click: function () {
appShell.hide();
}
},
{ label: 'Quick action' },
{
label: 'Exit',
accelerator: 'Command+Q'
}
]);
tray.setToolTip('This is my application.');
tray.setContextMenu(contextMenu);
});

This creates a custom tray icon with context menu in the notification area of your operating system.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.113.67