Communication between electron rendering processes

Time:2020-8-11

A collection of rookies’ electron stepping on the pit.

IPC is convenient for communication between the main process and the rendering process. But between rendering processes? Ha ha, my farmer seems to have stepped into a pit again.

Scheme 1:

Use global share properties:

// In the main process.
global.sharedObject = {
  someProperty: 'default value'
}
// In page 1.
require('electron').remote.getGlobal('sharedObject').someProperty = 'new value'
// In page 2.
console.log(require('electron').remote.getGlobal('sharedObject').someProperty)

But it has no event mechanism and no real communication function. Of course, this reminds me of the global object in node.

  • https://electron.atom.io/docs…

Scheme 2

Using the main process for message transfer: this scheme is still very good.

// In the main process.
ipcMain.on('ping-event', (event, arg) => {
  yourWindow.webContents.send('pong-event', 'something');
}

// In renderer process
// 1
ipcRenderer.send('ping-event', (event, arg) => {
    // do something
  }
)

// 2
ipcRenderer.on('pong-event', (event, arg) => {
    // do something
  }
)

Scheme 3

The remote interface is used to directly obtain the message sent by the rendering process

// renderer process
// get Window by ID
remote.BrowserWindow.fromId(winId).webContents.send('ping', 'someThing');

There are several ways for the rendering process to get the ID:

The first one: set and get through global
The first is: the main process creates events and sends information

// main process
win1.webContents.send('distributeIds',{
    win2Id : win2.id
});
win2.webContents.send('distributeIds',{
    win1Id : win1.id
});

The third kind: write a file or anything, the method is still various.

reference resources:

  • https://github.com/electron/e…

  • https://github.com/electron/e…

  • https://juejin.im/entry/58869…

API to understand:

  • https://electron.atom.io/docs…

  • https://electron.atom.io/docs…