在 Electron 中,我的主进程打开了一个 BrowserWindow。 BrowserWindow 加载一个 html 页面,然后同一个窗口最终加载另一个 html 页面。
主要.js
var mainWindow;
global.mainState = {
settings: {}
}
mainWindow = createWindow('main', {
width: 1000,
height: 800,
});
if (curState == 'load') {
mainWindow.loadURL(`file://${__dirname}/interface/load.html`, {})
}
if (curState == 'login') {
mainWindow.loadURL(`file://${__dirname}/interface/login.html`, {})
}
加载.html
const remote = require('electron').remote;
var testGlobal = remote.getGlobal('mainState')
testGlobal.settings = 'test value'
testGlobal.settings.inner = 'test value2'
当main.js加载第二页(login.html)时,全局变量会被删除/解引用吗?文档说,如果渲染器进程取消引用全局变量,那么该变量将被 gc'd。当我尝试对此进行测试时,我得到了不一致的结果,我只想得到比我更聪明的人的一些解释。
最佳答案
使用 IPC 设置全局值。
@RoyalBingBong 是正确的,因为“remote.getGlobal()
只是为您提供了 mainState
的副本,而不是引用。”
您似乎正在更改全局变量的值,但实际上并没有。因此,例如,当我刷新 Electron 浏览器窗口时,该全局变量的值将恢复为原来的值。
我发现正确更改全局变量值的唯一方法是使用 ipcMain
和 ipcRenderer
(冗长的方法)。
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!"
现在,我可以刷新我的 Electron 窗口或启动一个新的渲染器进程,全局变量的值将正确地成为我设置的值,在这个例子中,“你好!”。
您还可以看到,为了阅读它,我使用了更简单的 remote.getGlobal
。我还没有测试这是否会在值发生变化并且 this 的值没有得到更新时引起问题。如果是这种情况,我可能不得不回到这个答案并使用另一个 ipcMain
和 ipcRenderer
手动读取全局变量。
关于javascript - 如果渲染器进程关闭, Electron 全局变量垃圾会被收集吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45179884/