How to keep the electron app running in background

Viewed 19

Hello I am trying to create an electron app what I want the the app to do is on clicking the app close button I want the render to keep running in the background and go the the taskbar tray and make sure it can listen to any key Trigger.

I had written some code to make the app go the the tray and have a tray icon but it does not keep the app running the bg it moves it to tray and the options on the tray icon are not working as expected see this image for reference: enter image description here

now on clicking the show app it reloads the entire render and on quit it dosen't even quit the application.

Here is my main.js code:

// Modules to control application life and create native browser window
const { app, BrowserWindow, Menu, nativeImage, Tray } = require("electron");
const path = require("path");
let mainWindow;
let tray=null;
function createWindow() {
    // Create the browser window.
    if (!tray) {
        // if tray hasn't been created already.
        createTray();
    }
    let win = new BrowserWindow({
        width: 450,
        height: 240,
        webPreferences: {
            preload: path.join(__dirname, "preload.js"),
        },
        autoHideMenuBar: true,
    });
    win.loadURL("http://localhost:3000");

    win.on("close", function (event) {
        event.preventDefault();
        win.hide();
    });
    win.on("restore", function (event) {
        win.show();
        tray.destroy();
    });

    return win;
}

function createTray() {
    const icon = path.join(__dirname, "/public/favicon.ico"); // required.
    const trayicon = nativeImage.createFromPath(icon);
    tray = new Tray(trayicon.resize({ width: 16 }));
    const contextMenu = Menu.buildFromTemplate([
        {
            label: "Show App",
            click: () => {
                createWindow();
            },
        },
        {
          label: "Quit",
          onClick: () => {
            app.quit();
          },
        },
    ]);

    tray.setContextMenu(contextMenu);
}

app.whenReady().then(() => {
    mainWindow = createWindow();
});
app.on("activate", function () {
    if (BrowserWindow.getAllWindows().length === 0) createWindow();
});
app.on("window-all-closed", () => {
    if (process.platform !== "darwin") {
        app.quit();
    }
});
0 Answers
Related