I am working on a project with Electron and React. I am going to be making multiple calls to the database via ipcMain and ipcRenderer so I moved the calls for ipcMain to another file(ipcMainHandler.js).
The challenge I am facing now is how to send responses back to the ipcRenderer. I am unable to access the mainWindow from within that file.
This is the code for my main file.
const url = require('url');
const { app, BrowserWindow } = require('electron');
let mainWindow;
function createWindow() {
mainWindow = new BrowserWindow({
width: 800,
height: 600,
webPreferences: {
nodeIntegration: true,
enableRemoteModule: true,
preload: __dirname + '/preload.js'
},
});
const startUrl =
process.env.ELECTRON_START_URL ||
url.format({
pathname: path.join(__dirname, './build/index.html'),
protocol: 'file:',
slashes: true,
});
mainWindow.loadURL(startUrl);
mainWindow.webContents.openDevTools();
mainWindow.on('closed', function () {
mainWindow = null;
});
}
app.on('ready', createWindow);
app.on('window-all-closed', function () {
if (process.platform !== 'darwin') {
app.quit();
}
});
app.on('activate', function () {
if (mainWindow === null) {
createWindow();
}
});
require('./src/server/helpers/ipcMainHandler.js');
The ipcMainHandler.js file
const { SIGNIN_REQUEST, SIGNIN_RESPONSE } = require('../../common/events.js');
const { ipcMain } = require('electron');
ipcMain.on(SIGNIN_REQUEST, (event, data) => {
const user = AuthController.userSignin({ ...data });
});
Things I have tried
Accessing the currentWindow from remote - throws a remote undefined error
Adding the mainWindow to a global variable and trying to access it in the ipcHander. - This also returns an undefined message.
This has been resolved. I used the event object to send the response from ipcMain.
ipcMain.on(SIGNIN_REQUEST, async (event, data) => {
const user = await AuthController.userSignin({ ...data });
event.sender.send(SIGNIN_RESPONSE, user);
});
Related
I am trying achieve something where I can directly send data to react and where in react whenever it receives it does something.
So my electron.js is in below format.
// ./public/electron.js
const path = require("path");
const { app, BrowserWindow, ipcMain} = require("electron");
const isDev = false; //require("electron-is-dev"); //false
let splash = null;
let win = null;
let etmf_obj = null;
function createWindow() {
// Create the browser window.
win = new BrowserWindow({
width: 1920,
height: 1080,
webPreferences: {
nodeIntegration: true,
contextIsolation: true,
enableRemoteModule: true,
preload: path.join(__dirname, "./preloadDist.js"),
},
});
// win.loadFile("index.html");
win.loadURL(
isDev
? "http://localhost:3000"
: `file://${path.join(__dirname, "../build/index.html")}`
);
// Open the DevTools.
if (!isDev) {
win.webContents.openDevTools({ mode: "undocked" });
}
}
app.whenReady().then(createWindow);
app.on("window-all-closed", () => {
if (process.platform !== "darwin") {
app.quit();
}
});
app.on("activate", () => {
if (BrowserWindow.getAllWindows().length === 0) {
createWindow();
}
});
function restartApp() {
console.log("restarting app..");
app.exit();
app.relaunch();
}
//IPC SECTION
ipcMain.handle("notify", (event, args) => {
console.log("from react I got" + args);
console.log("hello from electron via react"); //this one works as expected
});
ipcMain.on("splashDone", function () {
console.log("splash done");
});
ipcMain.on("relaunchApp", function () {
restartApp();
});
ipcMain.on("closeAll", function () {
app.quit();
});
ipcMain.on("callAnim", function (args) {
win.webContents.send("showAnimation", args);// trying to send data directly to
//react here but don't know whether its right way or not
});
and my preload file preloadDist.js is in below format
const { ipcRenderer, contextBridge } = require("electron");
contextBridge.exposeInMainWorld("electron", {
notificationApi: {
sendNotification(message) {
ipcRenderer.invoke("notify", message);
},
},
batteryApi: {},
filesApi: {},
splashStatus: {
splashDone() {
ipcRenderer.invoke("splashDone")
}
},
});
and react to call function of or to send data I am do this
for example to send notification data :
<button
className="speak_border"
onMouseEnter={() => setHovermic(true)}
onMouseLeave={() => setHovermic(false)}
onClick={() => {
soundwave();
window.electron.notificationApi.sendNotification(
"From react Hi!");
}}
>
and to receive data I am not able to figure out but as I am doing win.webContents.send("showListenAnimation", args);
I am not able to understand how this will be received at the react end
what I tried is:
useEffect(() => {
try {
window.electron.on(
"showAnimation",
function (event, data) {
if (data) {
setAnim(true);
}
if (!data) {
setAnim(false);
}
}
);
} catch (e) {
console.log("issue with on getting data");
}
});
But this way I am getting error and not able to figure out the way to receive, but sending data from react to electron is working perfectly fine!
Please guide on this and how to achieve with about preload.js and electron.js
format.
I'm currently starting a new project with electron and react and I don't understand but I'm trying to use React devTools, I've tried some methods and none of them worked.
For instance, I followed here the method of electron-devtools-installer, which can be found here : https://github.com/MarshallOfSound/electron-devtools-installer
and when I launch the app the inspector still tells me
that
Download the React DevTools for a better development experience: https://reactjs.org/link/react-devtoolsYou might need to use a local HTTP server (instead of file://): https://reactjs.org/link/react-devtools-faq
Here is my main.js :
const { app, BrowserWindow, Notification, ipcMain } = require("electron");
const path = require("path");
const isDev = !app.isPackaged;
const {
default: installExtension,
REACT_DEVELOPER_TOOLS,
} = require("electron-devtools-installer");
let createWindow = () => {
const win = new BrowserWindow({
width: 800,
height: 600,
backgroundColor: "white",
title: "TaleSmith",
icon: path.join(__dirname, "../assets/icons/appIcon.png"),
webPreferences: {
nodeIntegration: false,
worldSafeExecuteJavaScript: true,
contextIsolation: true, // is a feature that ensures that both your preload scripts and Electron internal logical tun in separate context
preload: path.join(__dirname, "preload.js"),
},
});
win.loadFile(path.join(__dirname, "..", "src", "index.html"));
isDev && win.webContents.openDevTools();
};
if (isDev) {
require("electron-reload")(__dirname, {
electron: path.join(
__dirname,
"..",
"..",
"node_modules",
".bin",
"electron",
),
});
}
app.whenReady().then(async () => {
installExtension(REACT_DEVELOPER_TOOLS)
.then((name) => console.log(`Added Extension: ${name}`))
.catch((err) => console.log("An error occurred: ", err));
createWindow();
});
ipcMain.on("notify", (_, message) => {
new Notification({
title: "Hello World",
body: message,
}).show();
});
app.on("window-all-closed", () => {
if (process.platform !== "darwin") {
app.quit();
}
});
app.on("activate", () => {
if (BrowserWindow.getAllWindows().length === 0) {
createWindow();
}
});
Thanks a lot for your help !
Leverage the "dom-ready" event to initiate the dev tools instead of when the app is ready. Give this a try
const {
app,
BrowserWindow,
Notification,
ipcMain
} = require("electron");
const path = require("path");
const isDev = !app.isPackaged;
const {
default: installExtension,
REACT_DEVELOPER_TOOLS,
} = require("electron-devtools-installer");
let createWindow = () => {
const win = new BrowserWindow({
width: 800,
height: 600,
backgroundColor: "white",
title: "TaleSmith",
icon: path.join(__dirname, "../assets/icons/appIcon.png"),
webPreferences: {
nodeIntegration: false,
worldSafeExecuteJavaScript: true,
contextIsolation: true, // is a feature that ensures that both your preload scripts and Electron internal logical tun in separate context
preload: path.join(__dirname, "preload.js"),
},
});
win.loadFile(path.join(__dirname, "..", "src", "index.html"));
if (isDev) {
require("electron-reload")(__dirname, {
electron: path.join(
__dirname,
"..",
"..",
"node_modules",
".bin",
"electron",
),
});
// Errors are thrown if the dev tools are opened
// before the DOM is ready
win.webContents.once("dom-ready", async () => {
await installExtension([REACT_DEVELOPER_TOOLS])
.then((name) => console.log(`Added Extension: ${name}`))
.catch((err) => console.log("An error occurred: ", err))
.finally(() => {
win.webContents.openDevTools();
});
});
}
};
app.on("ready", createWindow);
ipcMain.on("notify", (_, message) => {
new Notification({
title: "Hello World",
body: message,
}).show();
});
app.on("window-all-closed", () => {
if (process.platform !== "darwin") {
app.quit();
}
});
app.on("activate", () => {
if (BrowserWindow.getAllWindows().length === 0) {
createWindow();
}
});
We are currently improve a project with electronjs: We have main.js for electron as you know and we have another html page that javascripts codes in it. We created a close button in this html page and this button should close the app but we cant reach main.js for close the app. Can you help me?
This code is from html page :
<div class="background-three link-container">
<button class="link-three" onclick="kapat()" id="kptbtn">Kapat</button>
</div>
<script>
function kapat(){
//what should I write here.
}
</script>
and this main.js
const { app, BrowserWindow } = require('electron')
const path = require('path')
function createWindow() {
const win = new BrowserWindow({
transparent: true,
frame: false,
resizable: false,
width: 500,
height: 700,
webPreferences: {
preload: path.join(__dirname, 'preload.js')
}
})
win.loadFile('girisEkrani.html')
}
app.whenReady().then(() => {
createWindow()
app.on('activate', () => {
if (BrowserWindow.getAllWindows().length === 0) {
createWindow()
}
})
})
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') {
app.quit()
}
})
You must use ipcMain and ipcRenderer. Main for reading message and Renderer for sending message.
.html page
<script>
function kapat() {
const { ipcRenderer } = require('electron')
const ipc = ipcRenderer;
ipc.send('kapat');
}
...
</script>
if you define ipc stuff out of the function it will not work and effect other functions.
main.js
const { app, BrowserWindow, ipcMain } = require('electron')
const path = require('path')
const ipc = ipcMain;
function createWindow() {
const win = new BrowserWindow({
transparent: true,
frame: false,
resizable: false,
width: 500,
height: 700,
webPreferences: {
nodeIntegration: true,
contextIsolation: false,
}
})
ipc.on('kapat', () => { win.close() })
win.loadFile('girisEkrani.html')
}
I'm struggling to pass a data from newly opened site window to renderer. What I want to achieve is to find a login button on site and listen on click event. I was reading about webview in electron, but I couldn't make It work. For now I'm stuck on window.open() method. Can you please point me what aspect I am missing? Here are my files:
//main.js
const {app, BrowserWindow, ipcMain} = require('electron')
const path = require('path')
function createWindow () {
const mainWindow = new BrowserWindow({
width: 800,
height: 600,
webPreferences: {
preload: path.join(__dirname, 'preload.js'),
nodeIntegration: true,
contextIsolation: false,
enableRemoteModule: true
}
})
mainWindow.loadFile('index.html')
// Open the DevTools.
mainWindow.webContents.openDevTools()
}
app.whenReady().then(() => {
createWindow()
app.on('activate', function () {
if (BrowserWindow.getAllWindows().length === 0) createWindow()
})
})
app.on('window-all-closed', function () {
if (process.platform !== 'darwin') app.quit()
})
ipcMain.on("open-login-window", () => {
console.info('dostal');
});
//renderer.js
const electron = require("electron");
const ipc = electron.ipcRenderer
const button = document.getElementById("login-button");
button.addEventListener("click", () => {
ipc.send("open-login-window")
const windowProxy = window.open('https://www.somesite.com/login', null, 'minimizable=false')
windowProxy.postMessage('hi', '*')
});
So I have this nightmarejs code I would like to execute(open new window and run the script) when you click a button inside an electron app. However I searched through the internet and nothing worked for me :/ (I have a mac)
var Nightmare = require('nightmare');
var nightmare = Nightmare({
electronPath: require('${__dirname}/node_modules/electron'),
show: true
});
nightmare
.goto('http://yahoo.com')
.type('form[action*="/search"] [name=p]', 'github nightmare')
.click('form[action*="/search"] [type=submit]')
.wait('#main')
.evaluate(function () {
return document.querySelector('#main .searchCenterMiddle li a').href
})
.end()
.then(function (result) {
document.getElementById("results").innerHTML = result;
})
.catch(function (error) {
console.error('Search failed:', error);
});
const electron = require('electron')
const app = electron.app
const BrowserWindow = electron.BrowserWindow
let mainWindow;
function createWindow() {
mainWindow = new BrowserWindow({
title: "Dummy",
fullscreenable: false,
resizable: false,
alwaysOnTop: false,
width: 420,
height: 250,
'web-preferences': {
'web-security': false
}
})
mainWindow.loadURL(`file://${__dirname}/index.html`)
mainWindow.on('closed', function() {
mainWindow = null
})
}
app.on('ready', createWindow)
app.on('window-all-closed', function() {
if (process.platform !== 'darwin') {
app.quit()
}
})
app.on('activate', function() {
if (mainWindow === null) {
createWindow()
}
})
Thanks,
Bertram
I don't see anything that will fire off the code you want to run.
If you gave it to me to make work, I'd do two things:
wrap the nightmare code in a function so you can
require("./mynighmare.js").sleepPoorly()
in your index.html, add a button that calls the above line to actually run your code.
... then I'd do a whole bunch of testing, because my first draft wouldn't work right :)