electron-safe-ipc
electron-safe-ipc is a safe communication library between the main process and renderer processes in Electron.
"Safe" means:
- Works even when
node-integration
==false
in renderer processes - Works without JS object instance sharing
It uses:
- JSON to pack data
- Electron
protocol
to send message to main process - Electron
WebContents.executeJavaScript
to send message to renderer process
Used in Wantedly, Inc.
Install
npm install --save electron-safe-ipc
Use
Main process
// in mainvar ipc = ; ipc;ipc;
Renderer process
Node style
If "node-integration"
is disabled, use bundling tools (e.g., browserify).
var ipc = ; ipc;
Traditional style (UMD)
<webview>
Communicate between renderer process and You can use electron-safe-ipc to communicate between renderer processes and webviews.
LIMITATION: you cannot use "electron-safe-ipc/host-webview"
multiple times (e.g., reloading renderer window or using multiple windows not supported).
// in renderervar ipc = ; ipc;ipc;
<!-- in webview -->
API
ipc
is an EventEmitter
.
ipc.send(channel: string, ...args)
Send a message between processes.
The arguments are packed into JSON.
The message is sent to all renderer processes when you call this from the main process.
ipc.on(channel: string, callback: (...args) => void)
Receive messages.
Other EventEmitter
methods can also be used to listen to messages.
ipc.request(requestName: string, ...args): Promise
Sends a request to the other side and get the response as Promise
.
var ipc = ; ipc ; ipc ;
ipc.respond(requestName: string, responder: (...args) => Promise|any)
Registers a responder for the request. responder
can return both Promise
and normal values.
var ipc = ; ipc; ipc;