在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
网友回复
qwen3-omni-flash-realtime实时音视频对话如何记住上下文聊天历史记录?
lmarena.ai如何内置html代码直接预览功能?
qwen3-omni-flash-realtime官方vad python示例代码实时语音聊天没有声音?
如何抵御自定义SSID信标帧攻击?
如果使用网页来搭建一个与gemini的视频聊天通话系统?
gemini如果调用mcp服务?
如何接入多模态ai的api例如gemini或qwen Omni实现ai视频面试打分并保存面试过程?
如何在win10上开发一个自己的拼音输入法?
列式json与传统json有啥不同,如何相互转换?
在哪可以查看任意域名网站的每天的流量?


