- 渲染进程项主进程发送消息,主进程并返回消息给渲染进程
//渲染进程 -某个组件页面
export default {
name: "ToolsBar",
created() {},
methods:{
message(){
//发送消息 并接受回调
ipcRenderer.invoke('test-01', "arg1", "").then(res=>{
this.$message(res)
})
},
...
}
}
//主进程 任意主进程的js文件中即可
//接收消息,并返回数据给消息发送者
ipcMain.handle('test-01', async (event, ...args) => {
console.log("收到了",new Date().getTime());
return "收到了 嘻嘻";
})
- 主进程向渲染线程发送消息
//主线程中发送消息
mainWindow.webContents.on('did-finish-load',() => {
setInterval(function (){
mainWindow.webContents.send('send-message-to-render-test', '这是主进程的主动搭讪')
},3000)
})
//子线程中全局监听事件
ipcRenderer.on('send-message-to-render-test', (event, arg) => {
console.log('渲染进程收到的消息:',arg)
})
问题:其他窗口渲染进程的主进程向别的窗口的渲染进程如何发送消息和接收消息?
备注:这句话问的就有问题,太小白了,经过一天的学习现在知道了,为什么没有接收到消息 electron 只有一个主进程和多个渲染进程
正确写法如下
//主进程
import {webContents,} from 'electron'
//在需要发送消息的地方-一下为发送消息的代码
//需要设置接收的渲染进程的ID
webContents.fromId(2).send("cookie",data)
//[错误示例]此前的写法-使用的是当前渲染进程的发送,所以从别的渲染进程中就只是发送到了他的渲染进程中
mainWindow.webContents.send('send-message-to-render-test', '这是主进程的主动搭讪')
//ID为2的渲染进程中监听主进程的消息
mounted() {
ipcRenderer.on("cookie",(e,res)=>{
console.log("cookie",res)
})
},