問題描述
在 Electron 中,我的主要進程打開了一個 BrowserWindow.BrowserWindow 會加載一個 html 頁面,然后同一個窗口最終會加載另一個 html 頁面.
In Electron, I have my main process opening a BrowserWindow. The BrowserWindow loads one html page and then the same window eventually loads another html page.
main.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.當我嘗試對此進行測試時,我得到了不一致的結果,我只想從比我更聰明的人那里得到一些解釋.
When main.js loads the second page (login.html), will the global variable be deleted/dereferenced? The docs say that if the renderer process dereferences a global variable then the variable will be gc'd. When I try to test this I get inconsistent results and I would just like some explanation from someone more wise than I.
推薦答案
testGlobal
將被垃圾回收,因為站點發生了變化.global.mainState
不會被刪除,但是當你調用 testGlobal.settings = 'test value'
時它也不會改變,因為 remote.getGlobal()
只是為您提供 mainState
的副本,而不是參考.
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.
我建議你使用 ipcMain 和 ipcRenderer 到自己同步全局變量.
I would suggest you use ipcMain and ipcRenderer to sync the global variable yourself.
這篇關于如果渲染器進程關閉,將收集電子全局變量垃圾?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!