Electron: Text in Tray Icon

A very common problem when working with menu bar electron apps is setting the tray icon to some dynamic text.

For example, what if you had an electron app that copied the 2FA auth code that was just sent to you via iMessage (sorry, shameless plug) and you wanted to change the icon momentarily to said code.

Here's what the final result looks like:

To achieve this effect, I used a library called merge-img, which simply horizontally concatenates png files. I used 10 number icons (png files), 0 through 9, and I create an image on the fly and set it as the icon.

This example below is Typescript, but you get the idea hopefully:

import * as mergeImg from 'merge-img'

// For example, the code argument below might be the string `123456`
function updateTrayIconWithCode (code: string, tray: Tray): void {
  const numberPaths = code.split('')
  .map(n => path.join(__dirname, `numbers/${n}.png`))

  mergeImg(numberPaths)
  .then((img: any) => {
    const numericalIcon = path.join(__dirname, 'numerical-icon.png')
    img.write(numericalIcon, () => {
      tray.setImage(numericalIcon)
    })
  })
}

Enjoy!