Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Emit custom events in electron app from main to renderer

So I know this works because I tried it, but it's not documented anywhere so I'm asking if it's OK to use this practice, and not worry that it would stop working in the future (Electron and nodejs are known to break things from one version to another)

This is the type of practice I'm talking about:

main.js

app.emit('did-something', param1, param2);

renderer.js (browser window)

const {app} = require('electron').remote;

app.on('did-something', (param1, param2) => {
  $('#whatever').text(param1);
});

Essentially I'm trying to move all the code that doesn't deal with HTML directly, like database interactions, into main.js and I want to make sure this is the right way to do it.

Also, is it ok if I extend the app object with my own methods and properties?

like image 760
Dawn Avatar asked Jan 16 '18 15:01

Dawn


People also ask

How do you send data from main to renderer in Electron?

Communicate asynchronously from the main process to renderer processes. The ipcMain module is an Event Emitter. When used in the main process, it handles asynchronous and synchronous messages sent from a renderer process (web page). Messages sent from a renderer will be emitted to this module.

What is Nodeintegration Electron?

Electron node integration refers to the ability of accessing Node. js resources from within the “renderer” thread (the UI). It is enabled by default in Quasar CLI, although Electron is encouraging developers to turn it off as a security precaution.

Will quit vs before quit?

quit() ​ Try to close all windows. The before-quit event will be emitted first. If all windows are successfully closed, the will-quit event will be emitted and by default the application will terminate.

What is preload JS in Electron?

A preload script contains code that runs before your web page is loaded into the browser window. It has access to both DOM APIs and Node. js environment, and is often used to expose privileged APIs to the renderer via the contextBridge API.


1 Answers

The main process should almost always only be used for creating BrowserWindows and for accessing electron APIs which are marked in the docs as only accessible via the main process.

Check out this article for more details of the differences between the main/renderer and what they are used for. The Chromium process architecture means that any blocking code in the main process will block the renderers too.

All your app code should be in render processes and if you're executing long-running processes these should be bumped into Web Workers or other renderer processes. electron-remote can help you do this.

If you want to communicate between the main and renderer processes you should use the documented API's.

like image 191
Tim Avatar answered Oct 26 '22 23:10

Tim