renderer.js
renderer.js
ipcRenderer.sendSync('setGlobal', 'globalVarName').varInner.varInner2 = 'result';
main.js
global.globalVarName = {
varInner: {
varInner2: ''
},
iWontChange: 'hi'
};
ipcMain.on('setGlobal', (event, arg) => {
console.log(arg) // should print "result"
// what goes here?
})
console.log(varInner2) // should print "result"
这样的事情是否可能,即以这种方式设置globalVarName
的varInner2
?其次,有没有办法对此进行优化,这样我们就不必为每个全局变量重写这个过程(即使用动态变量名的某种方式)?
Is something like this possible, namely setting the varInner2
of globalVarName
in this manner? Secondly, is there a way to optimize this so we wouldn't have to rewrite this process for every global variable (i.e. some way to do this with dynamic variable names)?
感谢任何想法或解决方案,如果这是一个常识性问题,请见谅.
I appreciate any ideas or solutions, sorry if this is a common sense question.
当您只对读取全局变量的值感兴趣时,使用 getGlobal
非常有用.但是,我发现尝试使用 getGlobal
分配或更改其值是有问题的.
Using getGlobal
works great when you're only interested in reading the value of the global variable. However, I found that trying to assign or change its value using getGlobal
to be problematic.
在我的例子中,我发现主进程上的全局变量并没有真正改变.具体来说,在开发中刷新 Electron 窗口时,全局变量被设置回原来的值.这使得在发展中恢复状态成为一个问题.
In my case, I found that the global variable on the Main process didn't actual change. Specifically, when refreshing the Electron window in development, the global variables were set back to their original value. This made restoring state in development an issue.
不确定这是否也发生在生产中,但我想它会发生,因此建立依赖于全局变量最新值的新流程将是有问题的.
Not sure if this also was occurring in production, but I imagine it would, so spinning up new processes that relied on up-to-date values of global variables would be problematic.
相反,我最终使用了 ipcMain
和 ipcRenderer
更详细的方法.
Instead, I ended up using the more verbose method of ipcMain
and ipcRenderer
.
main.js
const { ipcMain } = require( "electron" );
ipcMain.on( "setMyGlobalVariable", ( event, myGlobalVariableValue ) => {
global.myGlobalVariable = myGlobalVariableValue;
} );
renderer.js
const { ipcRenderer, remote } = require( "electron" );
// Set MyGlobalVariable.
ipcRenderer.send( "setMyGlobalVariable", "Hi There!" );
// Read MyGlobalVariable.
remote.getGlobal( "MyGlobalVariable" ); // => "Hi There!"
这篇关于在 Electron 中使用 ipc 从渲染器设置全局变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!