Main.js
const { app, BrowserWindow, ipcMain } = require('electron');
const url = require('url')
const path = require('path')
let mainWindow;
/**
* Create a new window
*/
const createWindow = () => {
mainWindow = new BrowserWindow({
webPreferences: {
/** Enable node integration */
nodeIntegration: true
}
});
/** Open devTools */
mainWindow.webContents.openDevTools();
/** Load the index.html page */
mainWindow.loadURL(url.format ({
pathname: path.join(__dirname, 'index.html'),
protocol: 'file:',
slashes: true
}))
};
/**
* Initialize the application
*/
const init = () => {
/** Create app window */
createWindow();
/** Define channel name and message */
const CHANNEL_NAME = 'main';
const MESSAGE = 'tick';
ipcMain.on(CHANNEL_NAME, (event, data) => {
/** Show the request data */
console.log(data);
mainWindow.webContents.send(CHANNEL_NAME, "hhhhhhhhhhhhhhhh");
/** Send a response for a synchronous request */
event.returnValue = 'pong';
});
/** Send message every one second */
setInterval(() => {
mainWindow.webContents.send('another', MESSAGE);
}, 1000);
};
/**
* Run the app
*/
app.on('ready', init);
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>IPC test app</title>
<script>
const { ipcRenderer } = require('electron');
/** Define channel name */
const CHANNEL_NAME = 'main';
/** Create a processor for a button's click event */
const clickButton = () => {
/** Message to be sent */
let message = 'ping';
/** Show response for a sync IPC request */
console.log(ipcRenderer.sendSync(CHANNEL_NAME, message));
}
/** Add IPC event listener */
ipcRenderer.on(CHANNEL_NAME, (event, data) => {
console.log('hiiiiiiii ' , data);
});
/** Add IPC event listener */
ipcRenderer.on('another', (event, data) => {
console.log('hello : ' , data);
});
</script>
</head>
<body>
<button onclick="clickButton()">Press me</button>
</body>
</html>