damien damien - 3 months ago 52
Javascript Question

How to pass parameters from main process to render processes in Electron

I have an Electron app that can open different windows.

On app launch the app open a set of window(s) (that load the same HTML and JS files) but with params to change each window displayed infos.

Example :

app.on('ready', async () => {
...
// open window for stuff 1
win1 = new BrowserWindow({
width: 1024,
height: 728
});
win1.loadURL(`file://${__dirname}/app/app.html?id=1`);

// open window for stuff 2
win2 = new BrowserWindow({
width: 1024,
height: 728
});
win2.loadURL(`file://${__dirname}/app/app.html?id=2`);


Obviously passing params in file:// path doesn't work.
I can't find a clear solution in Electron documentation or elsewhere on Internet to condition my rendered window to a param.

I can probably use IPC communication after window ready but it seems a little bit too complicated until I just want pass a variable to my child view.

P.S. : to be totally honest my application is built with React/Redux and the param I want to pass to view is the redux store key to listen for this view.

Answer

According atom source code the query string method is a reliable way to do that very simply, especially when we only need to pass a unique string param:

// main process
win1.loadURL(`file://${__dirname}/app/app.html?id=${id}`);

// rendered process
console.log(global.location.search);

https://github.com/electron/electron/issues/6504