# ipcMain
`ipcMain` 模塊是類
[EventEmitter](https://nodejs.org/api/events.html) 的實例.當在主進程中使用它的時候,它控制著由渲染進程(web page)發送過來的異步或同步消息.從渲染進程發送過來的消息將觸發事件.
## 發送消息
同樣也可以從主進程向渲染進程發送消息,查看更多 [webContents.send][web-contents-send] .
* 發送消息,事件名為 `channel`.
* 回應同步消息, 你可以設置 `event.returnValue`.
* 回應異步消息, 你可以使用
`event.sender.send(...)`.
一個例子,在主進程和渲染進程之間發送和處理消息:
```javascript
// In main process.
const ipcMain = require('electron').ipcMain;
ipcMain.on('asynchronous-message', function(event, arg) {
console.log(arg); // prints "ping"
event.sender.send('asynchronous-reply', 'pong');
});
ipcMain.on('synchronous-message', function(event, arg) {
console.log(arg); // prints "ping"
event.returnValue = 'pong';
});
```
```javascript
// In renderer process (web page).
const ipcRenderer = require('electron').ipcRenderer;
console.log(ipcRenderer.sendSync('synchronous-message', 'ping')); // prints "pong"
ipcRenderer.on('asynchronous-reply', function(event, arg) {
console.log(arg); // prints "pong"
});
ipcRenderer.send('asynchronous-message', 'ping');
```
## 監聽消息
`ipcMain` 模塊有如下監聽事件方法:
### `ipcMain.on(channel, listener)`
* `channel` String
* `listener` Function
監聽 `channel`, 當新消息到達,將通過 `listener(event, args...)` 調用 `listener`.
### `ipcMain.once(channel, listener)`
* `channel` String
* `listener` Function
為事件添加一個一次性用的`listener` 函數.這個 `listener` 只有在下次的消息到達 `channel` 時被請求調用,之后就被刪除了.
### `ipcMain.removeListener(channel, listener)`
* `channel` String
* `listener` Function
為特定的 `channel` 從監聽隊列中刪除特定的 `listener` 監聽者.
### `ipcMain.removeAllListeners([channel])`
* `channel` String (可選)
刪除所有監聽者,或特指的 `channel` 的所有監聽者.
## 事件對象
傳遞給 `callback` 的 `event` 對象有如下方法:
### `event.returnValue`
將此設置為在一個同步消息中返回的值.
### `event.sender`
返回發送消息的 `webContents` ,你可以調用 `event.sender.send` 來回復異步消息,更多信息 [webContents.send][web-contents-send].
[web-contents-send]: web-contents.md#webcontentssendchannel-arg1-arg2-
- 介紹
- 常見問題
- Electron 常見問題
- 向導
- 支持平臺
- 分發應用
- 提交應用到 Mac App Store
- 打包應用
- 使用 Node 原生模塊
- 主進程調試
- 使用 Selenium 和 WebDriver
- 使用開發人員工具擴展
- 使用 Pepper Flash 插件
- 使用 Widevine CDM 插件
- 教程
- 快速入門
- 桌面環境集成
- 在線/離線事件探測
- API文檔
- 簡介
- 進程對象
- 支持的 Chrome 命令行開關
- 環境變量
- 自定義的 DOM 元素
- File 對象
- <webview> 標簽
- window.open 函數
- 在主進程內可用的模塊
- app
- autoUpdater
- BrowserWindow
- contentTracing
- dialog
- globalShortcut
- ipcMain
- Menu
- MenuItem
- powerMonitor
- powerSaveBlocker
- protocol
- session
- webContents
- Tray
- 在渲染進程(網頁)內可用的模塊
- desktopCapturer
- ipcRenderer
- remote
- webFrame
- 在兩種進程中都可用的模塊
- clipboard
- crashReporter
- nativeImage
- screen
- shell
- 開發
- 代碼規范
- 源碼目錄結構
- 與 NW.js(原 node-webkit)在技術上的差異
- 構建系統概覽
- 構建步驟(OS X)
- 構建步驟(Windows)
- 構建步驟(Linux)
- 在調試中使用 Symbol Server