I'm trying to understand the communications between electrons main and renderer processes. The documentation https://github.com/electron/electron/blob/master/docs/api/remote.md states that the "remote module provides a simple way to do inter-process communication (IPC) between the renderer process and the main process."
However, the documentation is very sparse with regards to how to set it up.
I can get the IPC examples to work with my application which seems simple enough. In what scenarios should the remote module be used ?
From the remote docs:
In Electron, GUI-related modules (such as dialog, menu etc.) are only available in the main process, not in the renderer process. In order to use them from the renderer process, the ipc module is necessary to send inter-process messages to the main process.With the remote module, you can invoke methods of the main process object without explicitly sending inter-process messages, similar to Java's RMI. An example of creating a browser window from a renderer process:
const remote = require('electron').remote; const BrowserWindow = remote.BrowserWindow; var win = new BrowserWindow({ width: 800, height: 600 }); win.loadURL('https://github.com');
Basically the remote
module makes it easy to do stuff normally restricted to the main process in a render process without lots of manual ipc messages back and forth.
So, in a renderer process, instead of:
const ipc = require('electron').ipcRenderer;
ipc.send('show-dialog', { msg: 'my message' });
ipc.on('dialog-shown', () => { /*do stuff*/ });
(And then code in the main to do stuff in response to those messages).
You can just do this all in the renderer:
const remote = require('electron').remote;
const dialog = remote.require('dialog')
dialog.showErrorBox('My message', 'hi.');
The ipc module is not explicitly required (although it's happening for you behind the scenes). Not to say the two are mutually exclusive.
One further question when using remote. Is it possible to access a function that exists in the main process rather than a module ?
I think what you're really asking is: how can I share code between main/renderer processes and how do I require a module in the renderer?
EDIT: You can just require it like normal. An edge case of this is if your renderer window's current URL isn't pointed to a local file (not loaded using file://). If you're loading a remote URL, your require path needs to be absolute or you can use remote like I said below.
OLD:
This is another use case for remote
. For example:
remote.require('./services/PowerMonitor.js')
Note that using remote like that causes your code to be run in the context of the main process. That might have it's uses but I would be careful.
Built-in node modules or electron
be required like normal:
require('electron')
require('fs')
Can I access global variables from the renderer?
Yes.
//in main
global.test = 123;
//in renderer
remote.getGlobal('test') //=> 123