Rookie
Rookie

Reputation: 939

Why is the variable undefined? - Node - ElectronJs

I am creating an Electron app and I am trying to split my code in different scripts to make it more manageable; however, for some reason one of the variables in my script keeps returning undefined and I can't figure out why. I already checked similar questions here on SO, but did not find an answer.

I have a file called windowManipulation.js and this is part of it:

let signInWindow;

module.exports.createSignInWindow = () => {
    signInWindow = new BrowserWindow({
        show: false,
        width: 1500,
        height: 800,
        webPreferences: {
            nodeIntegration: true
        }
    });

    signInWindow.loadFile(`views/logIn.html`)

    signInWindow.once("ready-to-show", () => {
        signInWindow.show();
    });

    signInWindow.on("close", () => {
        signInWindow = null;
    });

    signInWindow.on('crashed', () => {
        app.relaunch();
        app.exit(0);
    })
}

module.exports.closeSignInWindow = () => {
        signInWindow.close();
        signInWindow = null;
}

Now, when I call the function to create the window it creates it without a problem. But when I call the function to close it, it says that signInWindow is undefined.

Why is it undefined if it was supposed to be set when the signInWindow was created? What am I doing wrong?

Upvotes: 1

Views: 250

Answers (1)

Alex Wayne
Alex Wayne

Reputation: 187252

It sounds like createSignInWindow and closeSignInWindow are being called from different processes. Being different processes, they each their own memory, and each would execute this file independently. So if you create the window in the main process, and close it from the window process, the window process will not think the variable exists.

So it sounds like you need to use ipcRenderer to communicate from the render to the main process so that it can close the window for you.

It'd be something like:

// renderer
const { ipcRenderer } = require('electron')
ipcRenderer.send('close-signin')

// main
const { ipcMain } = require('electron')
ipcMain.on('close-signin', closeSignInWindow)

Upvotes: 1

Related Questions