# 5.进程间通信

为什么需要进程间的通信?

xcooo

通讯方式: IPC(interprocess Communication)进程之间进行通讯, 事件驱动的方式驱动

渲染子进程

ipcRenderer

const {ipcRenderer}  = require('electron')

window.addEventListener('DOMContentLoaded', () => {
    ipcRenderer.send('message', {
        code: 200,
        msg: 'hello electron from child'
    })
    ipcRenderer.on('remessage', (event, arg)=> {
        console.log('接收主进程的消息: ' + arg)
        document.getElementById('app').innerHTML = arg
    })
})
1
2
3
4
5
6
7
8
9
10
11
12

主进程

ipcMain

const {app, BrowserWindow, ipcMain}  = require('electron')
const client = require('electron-connect').client

function createWindow() {
    // 主进程
    const win = new BrowserWindow({
        width:800,
        height: 600,
        // 在html使用node语法
        webPreferences: {
            nodeIntegration: true
        }
    })

    win.loadFile('index.html')
    client.create(win)

    // 主进程接收子进程的消息
    ipcMain.on('message',(event, arg) => {
        console.log(arg.msg)
        // 主进程回复子进程的消息
        event.sender.send('remessage','hello electron from parent')
    })
}

app.on('ready', createWindow)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
上次更新: 2021/2/21 下午7:52:17