首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >回复webContents.send

回复webContents.send
EN

Stack Overflow用户
提问于 2020-04-28 00:19:32
回答 1查看 378关注 0票数 2

我的理解是,您不能从呈现的进程回复从主进程发送的事件。当通信从渲染器进程传递到主进程时,您可以执行相同的操作:

代码语言:javascript
运行
复制
// Renderer process
ipcRenderer.invoke('some-name', someArgument).then((result) => {
  // ...
})

// Main process
ipcMain.handle('some-name', async (event, someArgument) => {
  const result = await doSomeWork(someArgument)
  return result
})

来源:https://github.com/electron/electron/blob/master/docs/api/ipc-renderer.md#ipcrendererinvokechannel-args

对于简单的撤销/重做,我需要与之相反的东西,这就是我目前正在使用的:

mainProcess.js:

代码语言:javascript
运行
复制
// somewhere in the menu template
{
  id: 'undo',
  label: 'Undo',
  accelerator: 'Command+Z',
  selector: 'undo:',
  click: () => {
    this.mainWindow.webContents.send('undo-request');
  }
},

// down in the main process
ipcMain.on('undo-response', (_event, { canUndo }) => {
  const appMenu = Menu.getApplicationMenu();
  const undoMenuItem = appMenu.getMenuItemById('undo');
  undoMenuItem.enabled = canUndo;
});

renderer.js:

代码语言:javascript
运行
复制
ipcRenderer.on('undo-request', () => {
  canvas?.getCommandStack().undo();
  ipcRenderer.send('undo-response', canvas?.getCommandStack().canUnod());
})

如果mainProcess也可以等待promise,则不需要额外的undo-response事件:

代码语言:javascript
运行
复制
// somewhere in the menu template
{
  id: 'undo',
  label: 'Undo',
  accelerator: 'Command+Z',
  selector: 'undo:',
  click: () => {
    this.mainWindow.webContents.send('undo-request').then(({ canUndo }) => {
      const appMenu = Menu.getApplicationMenu();
      const undoMenuItem = appMenu.getMenuItemById('undo');
      undoMenuItem.enabled = canUndo;
    });
  }
},

有没有办法向主进程发送的事件发送某种类型的回复?

EN

回答 1

Stack Overflow用户

发布于 2021-06-03 05:01:18

下面是一个在主进程和渲染器之间设置通信的简单示例,该通信是从主进程启动的:

main.js

代码语言:javascript
运行
复制
// check if the window is loaded, before
// sending a data through desired communication channel
mainWindow.webContents.on('did-finish-load', () => {
  // initiate the communication from 
  // the main process through the window object
  mainWindow.webContents.send('ping', 'Message: Ping!');
});

// setup a listener to receive data sent
// through desired communication channel
// expect the data from the renderer
ipcMain.on('pong', (event, arg) => {
  console.log(arg); // prints -> Message: Pong!
});

renderer.js

代码语言:javascript
运行
复制
// setup a listener to receive data sent
// through desired communication channel
// expect the data from the main process
ipcRenderer.on('ping', (event, arg) => {
  console.log(arg); // prints -> Message: Ping!
  // send back a reply to the main process
  event.sender.send('pong', 'Message: Pong!');
});

电子样板

https://github.com/VibingCreator/electron-boilerplate

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/61463427

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档