In my Electron project, I'm trying to make a module singleton by setting it as a global. Since I use jquery
in this module, I import it in the renderer process and then send it to the main via ipc and set it as global there. Here is related part of my code:
main.js:
ipcMain.on( "setGlobal", ( event, global_var) => {
global[global_var[0]] = global_var[1];
console.log(global_var);
event.returnValue = 1;
} );
renderer.js:
const favourites = require("./components/favourites");
console.log(favourites);
ipcRenderer.sendSync("setGlobal", ["favourites", favourites]);
console.log(remote.getGlobal("favourites"));
The outputs of console.log
s in the renderer process are in the image below:
And the output of the main process is:
[ 'favourites', { favourites: [] } ]
As you see, the object (module) I sent from the ipcRenderer is changed in the ipcMain, it lost its add
and init
functions. Do you have any idea what is the reason of this behavior and how to fix it?
PS: To be sure, I tested it with a simple objects that contains functions instead of require("favourites")
. They are also behaving in the same way. I did a workaround by using only the entities as global and passing them to all of the functions as arguments. However, it's not a good way in sense of code readability.