Home > OS >  how to call an index.js function from index.html
how to call an index.js function from index.html

Time:08-17

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.

CodePudding user response:

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

CodePudding user response:

You will be well served by understanding the "process model" in Electron -- just as with Chromium on which the latter is based, it uses one process that loads and executes the "main.js" script, and another which would load "index.html" and indirectly the "index.js" script. This is where Electron's interprocess communication comes in.

As part of the implementation of this model, practically, to cause a function that is available in "index.js", to be called, you need to send a message from the main process to the "renderer" process (if you read and understood the process model, you would know this is the process that loads your "index.html").

The message is sent by calling the send method on an object of the WebContents class, which I assume your Electron application creates as part of its main process, lets assume the object is referred to with contents:

contents.send("foo", "bar");

The above will send the message "bar" on channel "foo", but to receive and act on the message (in your case that would presumably be calling some function of your choosing), you need to set up a listener for the message in the "renderer" process, meaning for instance your index.js including the following (this will break a Web browser because the latter normally doesn't have a require function, in the very least):

require("electron").ipcRenderer.on("foo", message => {
    console.debug(message); /// This will dump "bar" on the Web console
});

Since the above code runs in the "renderer" process, you can have the listener (message => ...) invoke any function available there.

That is the idiomatic approach, anyway.

  • Related