I\'m using create-react-app (react-scripts v3.0.0) and electronjs (v5.0.1). I\'m trying to pass events from the renderer to main process using the \'icpMain\' module as desc
I fix this issue to add webPreferences:{ nodeIntegration: true,preload: '${__dirname}/preload.js}', in electron.js file and add preload.js file in your directory (I added in /public directory where my electron.js file exists)
electron.js
mainWindow = new BrowserWindow({
title: 'Electron App',
height: 650,
width: 1140,
webPreferences: {
nodeIntegration: true,
preload: `${__dirname}/preload.js`,
webSecurity: false
},
show: false,
frame: true,
closeable: false,
resizable: false,
transparent: false,
center: true,
});
ipcMain.on('asynchronous-message', (event, arg) => {
console.log(arg); // prints "ping"
event.reply('asynchronous-reply', 'pong');
});
preload.js
in preload.js file just add below line:
window.ipcRenderer = require('electron').ipcRenderer;
ReactComponent.js
Write below code in your component function i.e: myTestHandle()
myTestHandle = () => {
window.ipcRenderer.on('asynchronous-reply', (event, arg) => {
console.log(arg); // prints "pong"
});
window.ipcRenderer.send('asynchronous-message', 'ping');
}
myTestHandle();
or call myTestHandle function anywhere in your component
It looks like adding the preference:
var mainWindow = new electron.BrowserWindow({
...
webPreferences: {
nodeIntegration: true,
}
});
is needed to enable require in the renderer process.
Indeed, you have to set nodeIntegration to true in your BrowserWindow webPreferences since the version 5.0.0 the default values of nodeIntegration and webviewTag are false to improve security. Electron associated PR: 16235