In this lesson i want to talk about How to Show Custom Messages in ElectronJS, ElectronJS is framework that allows developers to build cross platform desktop applications using web technologies such as JavaScript, HTML and CSS. it is built on top of Chromium, the open source version of Google Chrome and Node.js which provides runtime environment for JavaScript.
for creating custom messages in ElectronJS, you can use ipcRenderer and ipcMain modules from electron package.
In the main process, you can use the ipcMain.on() method to listen for a custom message. for example following code in the main process listens for a message with the channel “custom-message” and logs the received message to the console:
1 2 3 4 |
const {ipcMain} = require('electron') ipcMain.on('custom-message', (event, arg) => { console.log(arg) // logs the received message }) |
In the renderer process, you can use ipcRenderer.send() method to send a custom message. for example following code in the renderer process sends a message with the channel “custom-message” and the message “Hello from the renderer”:
1 2 |
const {ipcRenderer} = require('electron') ipcRenderer.send('custom-message', 'Hello from the renderer') |
It is important to note that ipcRenderer module can only be used in the renderer process and ipcMain module can only be used in the main process.
This is just simple example you can use it to pass information between the main and renderer processes, you can also use it to trigger actions and events.
More on ElectronJS
- How to Build GUI Applications with JavaScript & ElectronJS
- Introduction to ElectronJS
- How to Build Custom Notification with ElectronJS
- Desktop Operations in ElectronJS
- How to Upload File in ElectronJS
- How to Change ElectronJS Window Color
This is the code for index.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
const { app, BrowserWindow } = require('electron') let win function createWindow () { // Create the browser window. win = new BrowserWindow({ width: 800, height: 600, webPreferences: { nodeIntegration: true } }) // and load the index.html of the app. win.loadFile('index.html') // Send a message to the renderer process win.webContents.send('custom-message', 'Hello from main process!'); } app.whenReady().then(createWindow) |
This is index.html
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Hello World!</title> </head> <body> <h1>Hello World!</h1> <script> const { ipcRenderer } = require('electron') // Listen for the message ipcRenderer.on('custom-message', (event, message) => { console.log(message) }) </script> </body> </html> |
You can also use the message to update the UI or show notification.