English 中文(简体)
Electron - System Tray
  • 时间:2024-11-03

Electron - System Tray


Previous Page Next Page  

System tray is a menu outside of your apppcation window. On MacOS and Ubuntu, it is located on the top right corner of your screen. On Windows it is on the bottom right corner. We can create menus for our apppcation in system trays using Electron.

Create a new main.js file and add the following code to it. Have a png file ready to use for the system tray icon.

const {app, BrowserWindow} = require( electron )
const url = require( url )
const path = require( path )

let win

function createWindow() {
   win = new BrowserWindow({width: 800, height: 600})
   win.loadURL(url.format ({
      pathname: path.join(__dirname,  index.html ),
      protocol:  file: ,
      slashes: true
   }))
}

app.on( ready , createWindow)

After having set up a basic browser window, we will create a new index.html file with the following content −

<!DOCTYPE html>
<html>
   <head>
      <meta charset = "UTF-8">
      <title>Menus</title>
   </head>
   <body>
      <script type = "text/javascript">
         const {remote} = require( electron )
         const {Tray, Menu} = remote
         const path = require( path )

         let trayIcon = new Tray(path.join(  , /home/ayushgp/Desktop/images.png ))

         const trayMenuTemplate = [
            {
               label:  Empty Apppcation ,
               enabled: false
            },
            
            {
               label:  Settings ,
               cpck: function () {
                  console.log("Cpcked on settings")
               }
            },
            
            {
               label:  Help ,
               cpck: function () {
                  console.log("Cpcked on Help")
               }
            }
         ]
         
         let trayMenu = Menu.buildFromTemplate(trayMenuTemplate)
         trayIcon.setContextMenu(trayMenu)
      </script>
   </body>
</html>

We created the tray using the Tray submodule. We then created a menu using a template and further attached the menu to our tray object.

Run the apppcation using the following command −

$ electron ./main.js

When you run the above command, check your system tray for the icon you used. I used a smiley face for my apppcation. The above command will generate the following output −

tray Advertisements