+
80
-

electron多个页面进程之前如何通讯?

electron多个页面进程之前如何通讯?

网友回复

+
0
-

在Electron的渲染进程中,像dialog、menu模块是不能使用的,只能在主进程中使用。要想在渲染进程中使用,就要进行主、渲染进程之间通信,有三种方式:

一、ipcMain与ipcRenderer

通过这两个模块可以实现进程之间的通信。

ipcMain 在主进程中使用,用来处理渲染进程发送的消息

ipcRenderer 在渲染进程中使用,用来发送信息给主进程或者接受主进程发来的消息

主进程:
const {ipcMain} = require('electron')

// 监听渲染程序发来的事件
ipcMain.on('something', (event, data) => {
	event.sender.send('something1', '我是主进程返回的值')
})
渲染进程:
const { ipcRenderer} = require('electron')

// 发送事件给主进程
ipcRenderer.send('something', '传输给主进程的值')

// 监听主进程发来的事件
ipcRenderer.on('something1', (event, data) => {
	console.log(data) // 我是主进程返回的值
})

二、remote模块

使用 remote 模块,可以调用main 进程对象的方法,而不需要显示发送 进程间的消息。
const { dialog } = require('electron').remote
dialog.showMessageBox({type: 'info', message: '在渲染进程中直接使用主进程的模块'})

webContents webContents负责主进程向渲染进程发消息。 它是BrowserWindow对象的一个属性。 主进程发消息:
const {app, BrowserWindow} = require('electron')

let win

app.on('ready', () => {

	win = new BrowserWindow({width: 800, height: 600})

	// 加载页面
	win.loadURL('./index.html')

	// 导航完成时触发,即选项卡的旋转器将停止旋转,并指派onload事件后。
	win.webContents.on('did-finish-load', () => {

	// 发送数据给渲染程序
	win.webContents.send('something', '主进程发送到渲染进程的数据')
})
})

三、渲染进程数据共享

可以使用localStorage 、sessionStorage来进程通信。

参考:https://blog.csdn.net/qq_41257129/article/details/105505892

我知道答案,我要回答