electron/docs/api/ipc-main-process.md

50 lines
1.3 KiB
Markdown
Raw Normal View History

# ipc (main process)
2013-08-14 22:43:35 +00:00
Handles asynchronous and synchronous message sent from a renderer process (web
page).
2013-08-14 22:43:35 +00:00
The messages sent from a renderer would be emitted to this module, the event name
2014-04-25 09:35:36 +00:00
is the `channel` when sending message. To reply a synchronous message, you need
to set `event.returnValue`, to send an asynchronous back to the sender, you can
use `event.sender.send(...)`.
2013-08-14 22:43:35 +00:00
It's also possible to send messages from main process to the renderer process,
see [WebContents.send](browser-window.md#webcontentssendchannel-args) for more.
2014-04-25 09:35:36 +00:00
An example of sending and handling messages:
2013-08-14 22:43:35 +00:00
2014-04-25 09:35:36 +00:00
```javascript
// In main process.
2014-04-25 09:35:36 +00:00
var ipc = require('ipc');
ipc.on('asynchronous-message', function(event, arg) {
console.log(arg); // prints "ping"
event.sender.send('asynchronous-reply', 'pong');
});
ipc.on('synchronous-message', function(event, arg) {
console.log(arg); // prints "ping"
2014-05-10 09:47:54 +00:00
event.returnValue = 'pong';
2014-04-25 09:35:36 +00:00
});
```
2013-08-14 22:43:35 +00:00
2014-04-25 09:35:36 +00:00
```javascript
// In renderer process (web page).
2014-04-25 09:35:36 +00:00
var ipc = require('ipc');
console.log(ipc.sendSync('synchronous-message', 'ping')); // prints "pong"
ipc.on('asynchronous-reply', function(arg) {
console.log(arg); // prints "pong"
});
ipc.send('asynchronous-message', 'ping');
```
2013-08-14 22:43:35 +00:00
## Class: Event
2013-08-14 22:43:35 +00:00
### Event.returnValue
2013-08-14 22:43:35 +00:00
2014-04-25 09:35:36 +00:00
Assign to this to return an value to synchronous messages.
2013-08-14 22:43:35 +00:00
### Event.sender
2013-08-14 22:43:35 +00:00
2015-03-27 12:46:26 +00:00
The `WebContents` that sent the message.