Improved IPC for Electron
- Enhance IPC Programming Experience
- Allow sending ipc message to specific window
- Allow sending ipc request and waiting for the reply in callback function
npm install --save electron-ipc-plus
npm start examples/${name}
main process
const ipcPlusM = require('electron-ipc-plus');
ipcPlusM.sendToWin(browserWin, 'app:say-hello', 'hello renderer process!', (err, message) => {
console.log(`renderer replied: ${message}`);
});
renderer process
const ipcPlusR = require('electron-ipc-plus');
ipcPlusR.on('app:say-hello', (event, message) => {
console.log(`main process said: ${message}`);
setTimeout(() => {
event.reply(null, 'hi main process!');
}, 500);
});
renderer process
const ipcPlusR = require('electron-ipc-plus');
ipcPlusR.sendToMain('app:say-hello', 'hello main process!', (err, message) => {
console.log(`main replied: ${message}`);
});
main process
const ipcPlusM = require('electron-ipc-plus');
ipcPlusM.on('app:say-hello', (event, message) => {
console.log(`renderer process said: ${message}`);
setTimeout(() => {
event.reply(null, 'hi renderer process!');
}, 500);
});
Just check if event.reply
exists:
ipcMain.on('app:say-hello', (event, message) => {
if ( event.reply ) {
event.reply(null, 'hi renderer process!');
}
});
Only the first reply will be handled, after that the session will be closed and the rest of replies will be ignored.
An error with the code 'EWINCLOSED'
will be sent to your reply handler.
ipcPlus.sendToWin(win, 'app:say-hello', (err, message) => {
if ( err && err.code === 'EWINCLOSED' ) {
console.error('Window closed');
}
});
An error with the code 'ETIMEDOUT'
will be sent to your reply handler.
ipcPlus.sendToWin(win, 'app:say-hello', (err, message) => {
if ( err && err.code === 'ETIMEDOUT' ) {
console.error('Target failed to reply you: timedout for 100ms');
}
}, 100);
I try to solve this problem by the code below:
app.on('browser-window-created', (event, browserWin) => {
// close all session once the window closed
browserWin.webContents.once('did-navigate', () => {
_closeAllSessionsInWin(browserWin);
});
});
The problem is 'did-navigate' will be triggerred at the first time we open the window and I disable the above solution and leave this to user. Currently the best way to solve it is wrapping your own reload function, and manually close all sessions in that wrapped function.
When running an Electron app that has several modules depends on different version of electron-ipc-plus
,
we will receive a warning message.
MIT © 2017 Johnny Wu