Electron global variable garbage collected if renderer process closes?

只愿长相守 提交于 2019-12-02 00:25:52

testGlobal will be garbage collected, since the site changes. global.mainState will not be deleted, however it will also not change when you call testGlobal.settings = 'test value', because remote.getGlobal() just gives you a copy of mainState and not a reference.

I would suggest you use ipcMain and ipcRenderer to sync the global variable yourself.

Use IPC to Set the Global's Value.

@RoyalBingBong is correct in that "remote.getGlobal() just gives you a copy of mainState and not a reference."

It might seems like you're changing the value of the global variable, but you're not. So, for example, when I refresh my Electron browser window, the value of that global variable would revert to what it was.

I found that the only way to properly change the value of the global variable was to use ipcMain and ipcRenderer (the verbose way).

main.js

const { ipcMain } = require( "electron" );

ipcMain.on( "setMyGlobalVariable", ( event, myGlobalVariable ) => {
  global.myGlobalVariable = myGlobalVariable;
} );

renderer.js

const { ipcRenderer, remote } = require( "electron" );

// Set MyGlobalVariable.
ipcRenderer.send( "setMyGlobalVariable", "Hi There!" );

// Read MyGlobalVariable.
remote.getGlobal( "MyGlobalVariable" ); // => "Hi There!"

Now, I can refresh my Electron window or spin up a new renderer process and value of the global variable will correctly be what I set it to, in this example, "Hi There!".

You can also see that for reading it, I use the simpler remote.getGlobal. I haven't tested whether this will cause problems when the value changes and the value of this doesn't get updated. I might have to come back to this answer if that's the case and use another ipcMain and ipcRenderer to manually read the global variable.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!