user3162266
user3162266

Reputation: 87

Electron - ipcRenderer not working in main.js

I just can't figure this out. If I'm correct, usually you use "ipcMain" in the main file (in my case main.js). But I use colon-ide, and ipcMain is defined somewhere else. I want to create a new window. Everything I need to create a new window is in the main.js file, but the signal is somewhere else. So I need to send a 'create-window' signal to main.js. In fact, I'm sending it from a file, where ipcMain is defined.

And here's the problem: When in main.js I use the following:

const ipc = require('electron').ipcRenderer;
ipc.on('someSignal', function (event, structure) {
     console.log("something");
});

I get an error, that ipc in undefined.

When I use the following:

const ipc = require('electron').ipcMain;
ipc.on('someSignal', function (event, structure) {
    console.log("something");
});

Nothing happens. It doesn't listen, and I believe I should only have one ipcMain, so this must be wrong.

What am I doing wrong? If you need more code, just tell me.

To elaborate, let me show you this: I've got a functions.js file, where the event is invoked. Please ignore the "structure" variable.

const ipc = require('electron').ipcMain;

function someFunction() {
    console.log("function is invoked");
    let structure = 0;
    mainWindow.webContents.send('someSignal', structure);
}

"someFunction" is being invoked at some point - I get that "function is invoked" message in console, so this part works.

In editor.js the ipcRenderer is defined, and if I place the listener function here:

const ipc = require('electron').ipcRenderer;

ipc.on('someSignal', function (event, structure) {
    console.log("something");
});

It works. "something" gets printed out.

But, I need to add the listener in main.js file, because that's where my function for creating new windows is. But the listener doesn't work there. If I use ipcRenderer it stays undefined and throws an error if I do the ipc.on function. If I use ipcMain it gets defined (typeof returns an object), so looks like this is what I have to use. But nothing happens.

Is this because I'm trying to send messages between 2 ipcMain? I might try to use a global function as a work around.

Upvotes: 1

Views: 2073

Answers (1)

Grant
Grant

Reputation: 115

To get access to the require("electron") API in the BrowserWindow, you need to enable nodeIntegration in the constructor.

var myWindow = new BrowserWindow({
  width:600,
  height:400,
  // --- below here ---
  webPreferences:{
    nodeIntegration:true
  }
  // --- above here ---
});

Upvotes: 0

Related Questions