Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”

This article also participated in the “Digitalstar Project” to win a creative gift package and creative incentive money

The Electron desktop application has two processes, the main process and the render process.

First, the main process and render process introduction

Main Process

  • When the application starts, a main process is created
  • An application has one and only one main process
  • Only the main process can proceedGUIAPI operation, namely callNative APIs

Renderer Process

  • Windows displays the interface through the rendering process, DOM manipulation, node JS
  • An application can have multiple renderers
  • Native APIs must be accessed through the host process, and ipc communication must be conducted with the host process first

The renderer sends a message to the main process

There are basically two apis used: ipcRenderer in the rendering process and ipcMain in the main process

The renderer sends asynchronous messages to the main process

// Render process script
const { ipcRenderer } = require('electron')
// Send asynchronous messages
btns[0].addEventListener('click'.() = > {
    ipcRenderer.send('msg1'.'This is an asynchronous message')})// Listen for messages
ipcRenderer.on('msg1Re'.(ev, data) = > {
    console.info(data)
})
// Main process script
const { ipcMain } = require('electron')
ipcMain.on('msg1'.(ev, data) = > {
    console.info(data)
    // Send a message to the renderer
    ev.sender.send('msg1Re'.'This is a feedback message from the autonomous process')})Copy the code

The renderer sends synchronization messages to the main process

// Render process script
const { ipcRenderer } = require('electron')
// Send a synchronization message
btns[1].addEventListener('click'.() = > {
    const result = ipcRenderer.sendSync('msg2'.'This is a message from sync.')
    console.info(result)
})
// Main process script
const { ipcMain } = require('electron')
ipcMain.on('msg2'.(ev, data) = > {
    console.info(data)
    // Feedback message
    ev.returnValue = 'This is a synchronous feedback message from the master process'
})
Copy the code

The main process sends a message to the renderer

// Main thread script
BrowserWindow.getFocusedWindow().webContents.send(
    'mtp'.'Main process sends message to renderer'
)
// Render process script
ipcRenderer.on('mtp'.(ev, data) = > {
    console.info(data)
})
Copy the code

4. Communication between renderers

Local storage-based communication between renderers

That is, localStorage is used

With the help of the main process, the communication between different renderers

// Initiates the rendering process for the message
ipcRenderer.send('mti'.'This is a message from Modal.')
/ / main process
ipcMain.on('mti'.(ev, data) = > {
    // Get the renderer process by id, and then pass the message
    BrowserWindow.fromId(mainId).webContents.send('mti2', data)
})
// The renderer that receives the message
ipcRenderer.on('mti2'.(ev, data) = > {
	console.info(data)
})
Copy the code

Use sendTo

The premise is that you need to know the ID of the webContents of the other render window and we’re going to use global to store the window ID

  const modalMain = new BrowserWindow({
  	width: 200.height: 200.parent: BrowserWindow.fromId(mainId), // If the parent window is closed, the child window is closed
	webPreferences: {
		nodeIntegration: true.contextIsolation: false}})global.sharedObject =  {
    modalMainWebContentsId: modalMain.webContents.id
  }
Copy the code

The ID value is then retrieved by getGlobal in the renderer process and sent by sendTo

let sharedObject = getGlobal('sharedObject') 
let modalMainWebContentsId = sharedObject.modalMainWebContentsId
ipcRenderer.sendTo(modalMainWebContentsId, 'do-some-work'.1)
Copy the code

Other renderers then listen for do-some-work to get messages

ipcRenderer.on('do-some-work'.(e, data) = > {
    console.info(data)
  })
Copy the code

Five, the remote

Gui-related modules (dialog, Menu, etc.) are only available in the main process, not in the renderer process. To use them in the renderer process, you must use the remote module. This allows you to call the methods of the main process without displaying messages between sending processes.

The remote acquisition mode varies with the Electron version. For example, create a window In the render process: In electron > 14.0.0:

  1. @ electron/remote installation
  2. Define the webPreferences property
webPreferences: {
    nodeIntegration: true.// contextIsolation is used to allow the renderer to use the Node API
    contextIsolation: false
}
Copy the code
  1. Main process script:
require('@electron/remote/main').initialize()
mainWindow.loadFile('index.html')
const contents = mainWindow.webContents
require('@electron/remote/main').enable(contents)
Copy the code
  1. Child process script
const { BrowserWindow } = require('@electron/remote')
Copy the code

In electron = = 14.0.0: refer to official documents: www.electronjs.org/docs/breaki… Enable webContents In electron < 14.0.0:

  1. Main process script:
{ webPreferences: { enableRemoteModule: true}}Copy the code
  1. Renderer script
const { BrowserWindow } = require('electron').remote
Copy the code

Several methods and properties of remote

  • remote.getCurrentWindow()

Returns BrowserWindow, the window to which this page belongs

  • Remote. GetCurrentWebContents ()

Returns webContents, the Web content of this page

  • remote.getGlobal(name)

Returns the global variable of name (for example, global[name]) in the main process.

  • remote.process

The Process object in the main process. This is the same as remote.getGlobal(‘process’), but has been cached.