- Electron 教程
- Electron - 主頁
- Electron - 概述
- Electron - 安裝
- Electron 如何工作?
- Electron - Hello World
- Electron - 構建 UI
- Electron - 檔案處理
- Electron - Node 核心庫
- 程序間通訊 (IPC)
- Electron - 系統對話方塊
- Electron - 選單
- Electron - 系統托盤
- Electron - 通知
- Electron - Web 檢視
- Electron - 音訊和影片捕獲
- Electron - 定義快捷鍵
- Electron - 環境變數
- Electron - 除錯
- Electron - 打包應用程式
- Electron - 資源
- Electron 的有用資源
- Electron - 快速指南
- Electron - 有用資源
- Electron - 討論
Electron - 程序間通訊
Electron 為我們提供了 2 個 IPC(程序間通訊)模組,它們是 **ipcMain** 和 **ipcRenderer**。
**ipcMain** 模組用於從主程序向渲染器程序非同步通訊。在主程序中使用時,該模組會處理從渲染器程序(網頁)傳送的非同步和同步訊息。從渲染器傳送的訊息會發送到此模組。
**ipcRenderer** 模組用於從渲染器程序向主程序非同步通訊。它提供了一些方法,以便你能夠從渲染器程序(網頁)向主程序傳送同步和非同步訊息。你還可以收到來自主程序的回覆。
我們將建立一個主程序和一個渲染器程序,它們將使用以上模組互相傳送訊息。
建立名為 **main_process.js** 的新檔案,其中包含以下內容 −
const {app, BrowserWindow} = require('electron')
const url = require('url')
const path = require('path')
const {ipcMain} = require('electron')
let win
function createWindow() {
win = new BrowserWindow({width: 800, height: 600})
win.loadURL(url.format ({
pathname: path.join(__dirname, 'index.html'),
protocol: 'file:',
slashes: true
}))
}
// Event handler for asynchronous incoming messages
ipcMain.on('asynchronous-message', (event, arg) => {
console.log(arg)
// Event emitter for sending asynchronous messages
event.sender.send('asynchronous-reply', 'async pong')
})
// Event handler for synchronous incoming messages
ipcMain.on('synchronous-message', (event, arg) => {
console.log(arg)
// Synchronous event emmision
event.returnValue = 'sync pong'
})
app.on('ready', createWindow)
現在建立一個新的 **index.html** 檔案,並新增以下程式碼。
<!DOCTYPE html>
<html>
<head>
<meta charset = "UTF-8">
<title>Hello World!</title>
</head>
<body>
<script>
const {ipcRenderer} = require('electron')
// Synchronous message emmiter and handler
console.log(ipcRenderer.sendSync('synchronous-message', 'sync ping'))
// Async message handler
ipcRenderer.on('asynchronous-reply', (event, arg) => {
console.log(arg)
})
// Async message sender
ipcRenderer.send('asynchronous-message', 'async ping')
</script>
</body>
</html>
使用以下命令執行應用程式 −
$ electron ./main_process.js
以上命令將生成以下輸出 −
// On your app console Sync Pong Async Pong // On your terminal where you ran the app Sync Ping Async Ping
建議不要在渲染器程序中執行繁重/阻塞任務的計算。始終使用 IPC 將這些任務委託給主程序。這有助於保持應用程式執行。
廣告