Reputation: 11
So I'm making an electron app and I can't figure out how I can call a function in the main.js file from index.html. I have looked for hours and even asked friends, but no one knows the answer.
So either it's so simple no one bothered to write it down or I'm doing something fundamentally wrong.
Upvotes: 0
Views: 994
Reputation: 9170
You will be well served by understanding the "process model" in Electron.
Just as with Chromium on which the latter is based, Electron uses one process that loads the "main.js" script, dubbed the main process, and another process which loads a HTML document ("index.html") which in turn may load a Web page script ("index.js"), dubbed the renderer process.
If your main process loads multiple HTML documents, you may have multiple renderer processes, but there is only one single main process for an Electron application.
To have a function defined in "main.js" (or a script it imports), be called all the way from a Web page script, you will need to [send a message from the renderer process to the main process], and receive it in the latter.
The message is sent by calling the send
method on the ipcRenderer
object that is part of Electron API, by a Web page script:
const { ipcRenderer } = require("electron");
ipcRenderer.send("foo", "bar");
The above will send the message "bar" on channel "foo". To receive and act on the message (in your case calling some function of your choosing), you can set up a listener for the message in your "main" script (e.g. main.js
) and call the desired function (some_func
below):
const { ipcMain } = require("electron");
ipcMain.on("foo", message => {
some_func();
});
That is the idiomatic approach, anyway.
Upvotes: 1
Reputation: 81
use ipcMain on the renderer
The ipcMain module is an Event Emitter. When used in the main process, it handles asynchronous and synchronous messages sent from a renderer process (web page). Messages sent from a renderer will be emitted to this module. https://www.electronjs.org/docs/latest/api/ipc-main/
example: https://www.electronjs.org/docs/latest/tutorial/dark-mode
Upvotes: 0