1

I am creating a tray-centric app where the following requirements should be met together:

  1. Clicking close on the main window will "hide" the main window instead of closing the app.
  2. Left clicking the tray icon will "show" the main window instead of the tray menu.
  3. Right clicking the tray will show the tray menu. Selecting "exit" from the tray menu will exit the app.

Here is the smallest possible representative code block:

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

let mainWindow
let tray

app.on('ready', _ => {
    mainWindow = new BrowserWindow()

    // Prevent window from closing and quitting app
    // Instead make close simply hide main window
    // Clicking on tray icon will bring back main window
    mainWindow.on('close', event => {
        event.preventDefault()
        mainWindow.hide()
    })

    const icon = nativeImage.createFromPath('assets/img/cricket.png')
    tray = new Tray(icon.resize({ width: 16, height: 16 }))
    tray.setIgnoreDoubleClickEvents(true)

    var trayMenu = Menu.buildFromTemplate([
        {
            label: 'Quit',
            click: _ => {
                console.log('Menu/Quit was clicked')
                app.quit()
            }
        }
    ]);
    tray.setContextMenu(trayMenu)

    // Prevent menu from being shown on left click
    // Instead make main window visible (if it had been invisible)
    tray.on('click', event => {
        console.log('tray left clicked')
        event.preventDefault
        mainWindow.show()
    })
    
})

However when running this election app, requirement 1 is met but not 3.

Alternatively, if I comment out this block of code:

    // mainWindow.on('close', event => {
    //     event.preventDefault()
    //     mainWindow.hide()
    // })

Requirement 3 is met but not 1.

This teaches me app.quit() relies upon the default event behavior of BrowserWindow.close event.

Is it possible in electron to have all 3 requirements met, or do internal event calls preclude this type of behavior? Is there anything I should focus my research on to resolve the problem?

Russ
  • 1,996
  • 3
  • 19
  • 31

1 Answers1

0

I've met the same question, and this answer works for me, all you need to do is to destroy tray before quit this app: tray icon doesn't close immediately on app.quit in electron