6

I've been fiddling around with electron's remote module. In my main-process I've created this variable:

global.storage = {};

My renderer-process is initialised with a file called startup.html.

win.loadURL('file://' + __dirname + '/startup.html')

In there, I include a javascript file containing the following function:

function enterMain(value){
    remote.getGlobal('storage').exmpl = value;
    window.location.replace('./general.html');
}

The value I'm passing is "hello", and when calling upon...

console.log(remote.getGlobal('storage').exmpl);

...after assigning the value it returns "hello", as it should. However, once the window location has been replaced to general.html, in which I include a javascript file containing this function:

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

...it returns undefined. Why? Can anyone help me make sense of this?

Himmelslaub
  • 105
  • 1
  • 8

1 Answers1

10

There are a few things in play here:

  • The remote module caches remote objects in the renderer process on first access.
  • Properties that are added to a remote object in the renderer process are not propagated back to the original object in the main process.
  • Navigation restarts the renderer process.

With that in mind here's what's probably going on in your code:

  1. remote.getGlobal('storage') creates a new remote object and caches it.
  2. remote.getGlobal('storage').exmpl = value adds a new exmpl property to the remote object in the cache but doesn't propagate it to the original object in the main process.
  3. window.location.replace('./general.html') restarts the renderer process which blows away the remote object cache.
  4. console.log(remote.getGlobal('storage').exmpl) creates a new remote object since the cache is empty, but since the original object in the main process doesn't have an exmpl property it's also undefined on the new remote object.

The remote module seems deceptively simple at first, but it has many quirks, most of which are undocumented and as such may change in the future. I would suggest limiting the use of the remote module in production code.

Vadim Macagon
  • 14,463
  • 2
  • 52
  • 45
  • 1
    I see, is there any way then to keep a variable stored between page-transitions, without relying on a server? – Himmelslaub Oct 24 '16 at 05:46
  • 2
    @Himmelslaub If you want to persist state between pages keep it in the main process (as you've been doing), but use the `ipcRenderer` and `ipcMain` modules to sync the state instead of the `remote` module. – Vadim Macagon Oct 24 '16 at 07:13
  • Thanks, I'll try that! – Himmelslaub Oct 24 '16 at 07:19
  • Thanks for providing such a clear answer, @VadimMacagon! For a simple example of how to use `ipcMain` and `ipcRenderer` to set a global variable value in the Main process, look at this answer: https://stackoverflow.com/a/52167197/293280 – Joshua Pinter Sep 04 '18 at 13:47