1
votes

I find it difficult to understand how to differentiate between the main process and the renderer in the code.

here is my file structure:

file structure

I want to write a method in the server side and call it in the front-end side.

where should I write it? in the main or renderer process?

and if I wrote the method inside js folder from above image, will it be considered in the main or renderer process?

1
What do you mean by "the server side"? Are you running a server somewhere? As for JavaScript in the js folder, that of course depends on where you import that JavaScript. - user94559
@smarx I have server but electron has its known node based on my research (correct me If am wrong). Can you please explain to me how to make the javascript method runs in the main process and how can I make it run in the renderer process? - Behrouz Riahi
@smarx The link doesn't open with me - Behrouz Riahi
I'm not sure how to help with that problem, sorry. - user94559

1 Answers

1
votes

I'm assuming that your main.js file is where you created your BrowserWindow(s). This is your main process and is where you would write your server side method.

In your main process you can create a method using ipcMain either asynchronously or synchronously like so:

// In main process.
const {ipcMain} = require('electron');
ipcMain.on('asynchronous-message', (event, arg) => {
  console.log(arg); // prints "ping"
  event.sender.send('asynchronous-reply', 'pong');
});

ipcMain.on('synchronous-message', (event, arg) => {
  console.log(arg);  // prints "ping"
  event.returnValue = 'pong';
});

You can then call this method in a render process (js running in the chromium instance) like so:

// In renderer process (web page).
const {ipcRenderer} = require('electron');
console.log(ipcRenderer.sendSync('synchronous-message', 'ping')); // prints "pong"

ipcRenderer.on('asynchronous-reply', (event, arg) => {
  console.log(arg); // prints "pong"
});
ipcRenderer.send('asynchronous-message', 'ping');

Writing a method in the js folder you show above would be part of a render process.

Hope this helps!