問題描述
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.
推薦答案
使用IPC設置全局值.
當您只對讀取全局變量的值感興趣時,使用 getGlobal
非常有用.但是,我發現嘗試使用 getGlobal
分配或更改其值是有問題的.
Use IPC to Set the Global's Value.
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
.
ma??in.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 從渲染器設置全局變量的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!