0

I'm creating an app that can go back and forth between Window 1 to Window 2. I keep both windows open but hide the one not currently in use using currentWindow.hide(). I want to increment a counter each time I come into Window 2. I tried to use the code from Using ipc in Electron to set global variable from renderer to set a global variable and increment it each time I come into Window 2:

main.js

ipcMain.on('setMyGlobalVariable', (event, myGlobalVariableValue) => {
  global.myGlobalVariable = myGlobalVariableValue;
});

renderer.js

lv = remote.getGlobal("MyGlobalVariable"); // Read
if (lv = null) lv = 0;
lv = lv + 1;
console.log(lv);
ipcRenderer.send("setMyGlobalVariable", lv); // Store New Value

Unfortunately, every time I come back to window 2, lv is null! Can this be done, or am I doing something wrong?

Mike
  • 13
  • 2
  • 4

1 Answers1

1

You don't say how you are managing the showing/hiding of the windows – so there are a few ways to do what you want.

You could keep it within the Main context by subscribing to the show event for the window you want to track and just directly increment the counter there. The focus even would work the same way, if you are not actually hiding the windows.

mainWindow.on('show', event => {
    global.sharedData.counter += 1;
    console.log('counter', global.sharedData.counter);
});

From the Render context – from the docs: How to share data between web pages?

You can't increment a global property directly from remote - this fails: remote.getGlobal("counter")+=1;

but you can change the contents of an object:
remote.getGlobal("sharedData").counter += 1;

Main.js

// initialize the container:
global.sharedData = {counter: 0};

// not needed but just for sanity check
ipcMain.on('app-message', (event, arg) => {
    switch (arg.event) {
        case "log counter":
            console.log('counter', global.sharedData.counter);

        break;
     }
});

Renderer context

  // wrapped in a button click function
  $("#counter-btn").on("click", function (e) {


    // *** this is the only line that matters ***   
    remote.getGlobal("sharedData").counter += 1;


    // sanity check
    let c = remote.getGlobal("sharedData").counter;
    console.log('counter', c);

    // tell main to show the value
    ipcRenderer.send('app-message', { event: "log counter" });
  })
spring
  • 18,009
  • 15
  • 80
  • 160
  • Great! Thank you - that worked. And since I'm new to both javascript and Electron thanks for including the comments (like *** this is the only line that matters *** ). That really helped. Is there anything I'm supposed to do to close this? – Mike Feb 23 '20 at 20:44
  • Glad to help. Electron is a lot of fun to work with. If you want to accept the answer, click the check mark in the left sidebar. – spring Feb 23 '20 at 21:57