电子的 remote.getGlobal() returns "undefined" 在 window.location.replace() 之后

electron's remote.getGlobal() returns "undefined" after window.location.replace()

我一直在摆弄电子的远程模块。 在我的主进程中,我创建了这个变量:

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);

...在分配值后 returns "hello",这是应该的。但是,一旦 window 位置被替换为 general.html,我在其中包含一个包含此函数的 javascript 文件:

$(document).ready(function(){
     console.log(remote.getGlobal('storage').exmpl);
});

...它 returns 未定义。 为什么?任何人都可以帮助我理解这一点吗?

这里有几件事在起作用:

  • remote 模块在首次访问时在渲染器进程中缓存远程对象。
  • 在呈现器进程中添加到远程对象的属性不会传播回主进程中的原始对象。
  • 导航重新启动渲染器进程。

考虑到这一点,您的代码中可能会发生以下情况:

  1. remote.getGlobal('storage') 创建一个新的远程对象并缓存它。
  2. remote.getGlobal('storage').exmpl = value 将新的 exmpl 属性 添加到缓存中的远程对象,但不会将其传播到主进程中的原始对象。
  3. window.location.replace('./general.html') 重新启动渲染器进程,这会清除远程对象缓存。
  4. console.log(remote.getGlobal('storage').exmpl) 创建一个新的远程对象,因为缓存是空的,但是由于主进程中的原始对象没有 exmpl 属性 它也是 undefined 在新的远程对象上。

remote 模块起初看似简单,但它有很多怪癖,其中大部分没有记录,因此将来可能会改变。我建议限制在生产代码中使用 remote 模块。