我一直在摆弄 Electron 的远程模块。
在我的主流程中,我创建了以下变量:
global.storage = {};
我的渲染器进程由一个名为startup.html的文件初始化。
win.loadURL('file://' + __dirname + '/startup.html')
在其中,我包含一个包含以下功能的javascript文件:
function enterMain(value){
remote.getGlobal('storage').exmpl = value;
window.location.replace('./general.html');
}
我传递的值是“hello”,并在调用时...
console.log(remote.getGlobal('storage').exmpl);
...分配值后,它应返回“hello”。但是,一旦窗口位置被替换为general.html,我将在其中包含一个包含此功能的javascript文件:
$(document).ready(function(){
console.log(remote.getGlobal('storage').exmpl);
});
...返回未定义。
为什么?任何人都可以帮助我理解这一点吗?
最佳答案
这里有一些事情在起作用:
remote
模块在渲染器进程中缓存远程对象。 考虑到这一点,这就是您的代码中可能正在发生的事情:
remote.getGlobal('storage')
创建一个新的远程对象并对其进行缓存。 remote.getGlobal('storage').exmpl = value
将新的exmpl
属性添加到缓存中的远程对象,但在主进程中不会将其传播到原始对象。 window.location.replace('./general.html')
重新启动渲染器进程,这将破坏远程对象缓存。 console.log(remote.getGlobal('storage').exmpl)
由于缓存为空而创建了一个新的远程对象,但是由于主进程中的原始对象没有exmpl
属性,因此它在新的远程对象上也为undefined
。 remote
模块乍一看似乎很简单,但是它有很多怪癖,其中大多数没有记录,因此将来可能会改变。我建议限制在生产代码中使用remote
模块。