Skip to content
This repository has been archived by the owner on Feb 25, 2020. It is now read-only.

Background processes in electron

Rebekah Berriman edited this page Apr 6, 2019 · 3 revisions

Background processes in electron

This page contains a short guide intended to give developers a head start on creating background tasks in electron.

Electron processes

In electron, there are two types of processes: the main process, and the renderer process.

The main process is the entry point of the program and it performs any work to do with opening new windows (web pages) and managing each one's lifecycle.

A renderer process runs within a "web page", which in electron is just a window. Each renderer process manages everything GUI-related for its associated window and any function calls made by the GUI are run in this process. A consequence of this is that if a long-running task is run in a renderer process, its associated window will freeze and become unresponsive. So if you have a long-running task, you should delegate it to a background process.

To read more about electron's process architecture, see here

Creating background processes

A background process in electron is just a new window that has its visibility set to false. This should be initialized in the main process - i.e. in the index.js file.

We can trigger the start of a background task by sending messages between the renderer processes, via the main process. Communication between main and renderer processes is done via the ipcRenderer and ipcMain modules in electron.

For example:

index.js
...
import { ipcMain } from 'electron';

// maintain a reference to the background window so we can send messages to it
let bgProcess;

app.on('ready', () => {
  // wait for a start message then create and start the background process
  ipcMain.on('start', () => {
    bgProcess = new electron.BrowserWindow({ show: false });

    // backgroundtask.html contains a script tag referencing backgroundTask.ts
    bgProcess.loadURL('file://' + __dirname + '/path/to/backgroundTask.html');

    bgProcess.webContents.send('start', parametersGoHere);
  });

  ipcMain.on('finish', (event, params) => {
    // pass params back to the main window.
  });
});
backgroundTask.ts
...
import { ipcRenderer } from 'electron';

ipcRenderer.on('start', (event, parameters) => {
  // perform long running task
  event.sender.send('finished', params);
});