我一直在摆弄电子的远程模块。在主进程中,我创建了这个变量:
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);
});
…它返回undefined。为什么?有人能帮我弄明白吗?
这里有几件事在起作用:
-
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
模块。