how to run a background service in electron js?

18,450

Solution 1

Electron is not designed to run in background. If you are closing application then it will terminate all processes related with it. Electron is only used to provide GUI layer. After all it is hybrid application and it doesn't interact with core OS services to live itself like background service.

Apart from this there are two options:

  1. If you write a service with something else, say a node or .net application, then you probably could use Electron to interact with that service (via bundled Node accessing Windows APIs).
  2. Create feature like system tray. Minimise application to system tray.

Ref Link

Solution 2

You can use tray. here is an example (source):

"use strict";

// [run the app]
// $ npm install electron
// $ ./node_modules/.bin/electron .

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

let top = {}; // prevent gc to keep windows

app.once("ready", ev => {
    top.win = new BrowserWindow({
        width: 800, height: 600, center: true, minimizable: false, show: false,
        webPreferences: {
            nodeIntegration: false,
            webSecurity: true,
            sandbox: true,
        },                                
    });
    top.win.loadURL("https://google.com/");
    top.win.on("close", ev => {
        //console.log(ev);
        ev.sender.hide();
        ev.preventDefault(); // prevent quit process
    });

    // empty image as transparent icon: it can click
    // see: https://electron.atom.io/docs/api/tray/
    top.tray = new Tray(nativeImage.createEmpty());
    const menu = Menu.buildFromTemplate([
        {label: "Actions", submenu: [
            {label: "Open Google", click: (item, window, event) => {
                //console.log(item, event);
                top.win.show();
            }},
        ]},
        {type: "separator"},
        {role: "quit"}, // "role": system prepared action menu
    ]);
    top.tray.setToolTip("hello electrol");
    //top.tray.setTitle("Tray Example"); // macOS only
    top.tray.setContextMenu(menu);

    // Option: some animated web site to tray icon image
    // see: https://electron.atom.io/docs/tutorial/offscreen-rendering/
    top.icons = new BrowserWindow({
        show: false, webPreferences: {offscreen: true}});
    top.icons.loadURL("https://trends.google.com/trends/hottrends/visualize");
    top.icons.webContents.on("paint", (event, dirty, image) => {
        if (top.tray) top.tray.setImage(image.resize({width: 16, height: 16}));
    });
});
app.on("before-quit", ev => {
    // BrowserWindow "close" event spawn after quit operation,
    // it requires to clean up listeners for "close" event
    top.win.removeAllListeners("close");
    // release windows
    top = null;
});

Solution 3

Yes, it is possible by using electron-process npm library. ref :- https://www.npmjs.com/package/electron-process

First you will have to register the module which you want to run in background, just create simple background.html,

--background.html-- add below lines in script tag,

const background = require('electron-process').background;      
background.registerModule(require('../main/snippets/SnippetsManager'));

In main process just create one browser window in which your background.html will run and keep it as hidden window,

--main.js--

app.once("ready", ev => {
    service = new BrowserWindow({
        width: 80, height: 60, center: true, minimizable: false, show: false,
        webPreferences: {
            nodeIntegration: false,
            webSecurity: true,
            sandbox: true,
        },
    });
    service.loadURL("file://' + __dirname + '/background.html");
    service.on("close", ev => {
        ev.sender.hide();
        ev.preventDefault(); // prevent quit process
    });
});

Hope it helped, Regards.

Share:
18,450
Hitesh Soni
Author by

Hitesh Soni

Updated on June 16, 2022

Comments

  • Hitesh Soni
    Hitesh Soni almost 2 years

    How to implement background service using electron.

    i'm having a trouble can anyone tell me how to start a background service using electron which runs even after closing the app. i have tried many solutions but all of them stop the service after closing the app.