jaketrent / demo-electron-directory

Short example on how to communicate from Main to Renderer
https://jaketrent.com/post/select-directory-in-electron/
Creative Commons Zero v1.0 Universal
10 stars 3 forks source link

Sending messages back to the web view #9

Open cpgb85 opened 2 years ago

cpgb85 commented 2 years ago

What is the method for sending messages back to the web view?

AnEmortalKid commented 2 years ago

Here's a couple of ways I've discovered it can be done:

Using event sender and a listener on the renderer

main.js

ipcMain.on('select-directory', async (event, arg) => {
  const result = await dialog.showOpenDialog(win, {
    properties: ['openDirectory']
  });
  console.log('directories selected', result.filePaths)
  event.sender.send('select-directory-response', result.filePaths);
});

renderer.js

I'm using ipcRenderer and node enabled in my renderer

ipcRenderer.on('select-directory-response', (event, data) => {
  console.log(data);
});

But if not, just placing this on the preload.js should alwo work:

ipcRenderer.on('select-dirs-response', (event, args) => {
  alert(args);
});

Using ipc.handle

Following this doc

main.js

Define a handle that can be invoked by the preload.

ipcMain.handle('select-dirs-handle', async (event, ...args) => {
  const result = await dialog.showOpenDialog(mainWindow, {
    properties: ['openDirectory']
  })
  console.log('directories handled', result.filePaths)
  return result.filePaths
})

In preload, add another event.data.type for the different name and use async and await:

    if (evt.data.type === 'select-dirs-handle') {
      const result = await ipcRenderer.invoke('select-dirs-handle');
      alert(result);
    }

Working examples here https://github.com/jaketrent/demo-electron-directory/compare/master...AnEmortalKid:master

blastframe commented 2 years ago

@AnEmortalKid Thank you for this fix!

AnEmortalKid commented 2 years ago

Np, I made a pr since i forgot that part.