Electron.js How to minimize/close window to system tray and restore window back from tray?
I actually figured it out a long time ago but for folks who encounter the same problem here is one way you could achieve minimizing to tray
and restoring from tray
. The trick is to catch the close
and minimize
events.
var BrowserWindow = require('browser-window'),var mainWindow = new BrowserWindow({ width: 850, height: 450, title: "TEST", icon:'./icon.png'});mainWindow.on('minimize',function(event){ event.preventDefault(); mainWindow.hide();});mainWindow.on('close', function (event) { if(!application.isQuiting){ event.preventDefault(); mainWindow.hide(); } return false;});
and restoring from Tray
var contextMenu = Menu.buildFromTemplate([ { label: 'Show App', click: function(){ mainWindow.show(); } }, { label: 'Quit', click: function(){ application.isQuiting = true; application.quit(); } }]);
Addition to above answers - isQuiting
flag is worth setting at app' before-quit
callback, too. This way the application will be closed properly if requested by the OS or user some other way, e.g. via Macos Dock taskbar' quit command. Complete Typescript-friendly snippet:
import {app, BrowserWindow, Tray, Menu} from 'electron';import * as path from 'path';let window;let isQuiting;let tray;app.on('before-quit', function () { isQuiting = true;});app.on('ready', () => { tray = new Tray(path.join(__dirname, 'tray.png')); tray.setContextMenu(Menu.buildFromTemplate([ { label: 'Show App', click: function () { window.show(); } }, { label: 'Quit', click: function () { isQuiting = true; app.quit(); } } ])); window = new BrowserWindow({ width: 850, height: 450, show: false, }); window.on('close', function (event) { if (!isQuiting) { event.preventDefault(); window.hide(); event.returnValue = false; } });});
I updated the code with a scenario if you want to show icon on your system tray all the time until you don't quit the application
var { app, BrowserWindow, Tray, Menu } = require('electron')var path = require('path')var url = require('url')var iconpath = path.join(__dirname, 'user.ico') // path of yvar winfunction createWindow() { win = new BrowserWindow({ width: 600, height: 600, icon: iconpath }) win.loadURL(url.format({ pathname: path.join(__dirname, 'index.html'), })) var appIcon = new Tray(iconpath) var contextMenu = Menu.buildFromTemplate([ { label: 'Show App', click: function () { win.show() } }, { label: 'Quit', click: function () { app.isQuiting = true app.quit() } } ]) appIcon.setContextMenu(contextMenu) win.on('close', function (event) { win = null }) win.on('minimize', function (event) { event.preventDefault() win.hide() }) win.on('show', function () { appIcon.setHighlightMode('always') })}app.on('ready', createWindow)