electron

Electron tray icon change depending on dark theme?


I'm using Electron and trying to develop a tray (menubar) application.

enter image description here

I know how to set the icon:

const {Tray} = require('electron')
appIcon = new Tray('/path/to/my/icon')

How can I create an icon (or select a different one) that will change color depending on the theme (normal or dark) that the user has selected?

In the above example, I use a dark theme, so I can create a white icon, but what happens when the user has the normal white theme?


Solution

  • You should be using a template image (only black and clear colors): https://github.com/electron/electron/blob/master/docs/api/native-image.md#template-image

    That way macOS automatically adjusts your tray icon to be black when on normal theme, and white when on dark theme.

    Ensure the filename ends in Template.png or it won't work! Also include a @2x.png version if you target hi-dpi devices.

    So your folder would look like:

    .
    ├── main.js
    ├── IconTemplate.png
    └── IconTemplate@2x.png
    

    Then in your main.js:

    const {Tray} = require('electron')
    appIcon = new Tray('./IconTemplate.png')