A simple tool that lets you interact between processes in an ElectronJS app.
To install:
> npm i electron-sender
or
> npm install electron-sender
For developement environments, please use the --save-dev
flag when installing.
To use:
const { app, BrowserWindow } = require("electron");
const Sender = require("electron-sender");
app.on("ready", () => {
const mainWindow = new BrowserWindow({ ... });
mainWindow.webContents.loadFile(__dirname + "/index.html");
Sender.append(mainWindow);
Sender.receive(mainWindow, "test_function", (param1, param2) => {
console.log("Received param1: " + param1 + "\nReceived param2: " + param2);
});
});
<!DOCTYPE html>
<html>
<body>
<script>
Sender.send("test_function", ["string1", "string2"]);
</script>
</body>
</html>
And the output:
> Launch app
> Window opens
> Console message
> Received param1: String "string1"
> Received param2: String "string2"
Messages between processes are very simple.
Messages from main.js
to index.html
occur when a default function built-in called WebContent.executeJavascript
executes a function defined in the renderer process (index.html).
Example:
mainWindow.webContents.executeJavascript(`Sender.functions["test_function"]("string1", "string2")`);
// Is the same as
Sender.send("test_function", ["string1", "string2"]);
<script>
Sender.functions["test_function"] = (param1, param2) => {
console.log(param1, param2);
};
// Is the same as
Sender.receive("test_function", (param1, param2) => {
console.log(param1, param2);
});
</script>
This process works the same way, send
to receive
in the main process, send
to receive
in the renderer process, Vice-Versa.
This function prepares a certain ElectronJS process (window) for this package.
Basically it just gives the window the tools you need to interact between processes.
This function works with both main and renderer processes, as well as Sender.receive
.
This will listen for the specified message and run the defined function by Sender.receive
.
Like mentioned, both send
and receive
functions are necessary for interaction.
This function is very important because you need a function to run using Sender.send
, so without this, the package is useless.
This error occurs when using Sender.send
could not find the function name defined by Sender.receive
MIT