In Electron, the ipcRenderer module is used to send asynchronous messages from the renderer process (typically a web page) to the main process. Multiple parameters can be sent during this process, such as strings, numbers, objects, or arrays. Below, I will demonstrate how to use ipcRenderer to send multiple parameters with an example.
First, ensure that Electron is correctly installed and imported in your project, and that ipcMain is imported in the main process to receive messages.
Setting Up the Main Process
In the main process (typically the main.js file), you need to set up a listener to receive messages sent from the renderer process:
javascriptconst { app, BrowserWindow, ipcMain } = require('electron'); app.on('ready', () => { let mainWindow = new BrowserWindow({ webPreferences: { nodeIntegration: true } }); mainWindow.loadFile('index.html'); // Load the renderer process // Listen for messages sent from the renderer process ipcMain.on('message-from-renderer', (event, arg1, arg2, arg3) => { console.log(`Received parameters: ${arg1}, ${arg2}, ${arg3}`); // Process data from the renderer }); }); app.on('window-all-closed', () => { app.quit(); });
Setting Up the Renderer Process
In the renderer process (e.g., a script in an HTML page), you can use ipcRenderer to send messages:
html<!DOCTYPE html> <html> <head> <title>Electron Example</title> </head> <body> <h1>Electron IPC Example</h1> <button id="send">Send Message</button> <script> const { ipcRenderer } = require('electron'); document.getElementById('send').addEventListener('click', () => { // Send a message with multiple parameters to the main process ipcRenderer.send('message-from-renderer', 'Hello', 123, { key: 'value' }); }); </script> </body> </html>
In this example, when the user clicks the button on the page, the renderer process sends a message message-from-renderer to the main process using the ipcRenderer.send method, passing three parameters: a string 'Hello', a number 123, and an object { key: 'value' }.
After this setup, whenever the button in the renderer process is clicked, the main process receives these parameters and can see them printed in the console.