Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can we send messages main process to renderer process in Electron

I'm playing with electron for the first time. Trying to create a text editor

In render I'm sending a message to indicated the content has changed and needs saving:

document.getElementById('content').onkeyup = e => {   ipcRenderer.send('SAVE_NEEDED', {     content: e.target.innerHTML,     fileDir   }) } 

Then ipcMain receives it no problem. On the menu I have this:

{   label: 'Save',   click: _ => {      saveFile(message)      // trying:      // ipcMain.send('SAVED', 'File Saved')      },      accelerator: 'cmd+S', // shortcut } 

So that the user knows the files has have. But that doesn't seem to work. Is there any other way to do this? I would have thought "save" would be a pre-created role (sort of)

like image 293
relidon Avatar asked Sep 01 '18 03:09

relidon


People also ask

How do I send a message from Main to renderer Electron?

To send a message back to the renderer you would use: win. webContents. send('asynchronous-message', {'SAVED': 'File Saved'});

What is main process and renderer process in Electron?

Electron uses multi-process architecture to manage the application state and user interface. The main process controls the state of the application while the renderer process controls the user interface. Electron uses GPU process to perform graphically intensive tasks but it's optional.

How do electrons communicate?

In Electron, processes communicate by passing messages through developer-defined "channels" with the ipcMain and ipcRenderer modules. These channels are arbitrary (you can name them anything you want) and bidirectional (you can use the same channel name for both modules).


1 Answers

To send a message back to the renderer you would use:

win.webContents.send('asynchronous-message', {'SAVED': 'File Saved'}); 

And receive it like this:

ipcRenderer.on('asynchronous-message', function (evt, message) {     console.log(message); // Returns: {'SAVED': 'File Saved'} }); 

Where asynchronous-message is simply the channel you're sending it to. It can literally be anything.

webContents.send Docs

like image 87
Joshua Avatar answered Oct 18 '22 14:10

Joshua