3

I am learning to live without remote in my electron app. I have got to the point where I need to open a file from the renderer, which I understand required the main process to show the file dialog and send back the results.

In my main.js, I have the following:

ipcMain.on('open-file',(event,data)=>{
    dialog.showOpenDialog(null, data, (filePaths) => {
        event.sender.send('open-file-paths', filePaths);
    });
});

In my render process, which I call pager.js, I have the following:

ipcRenderer.send('open-file',{
    title: 'Title',
    defaultPath: localStorage.getItem('defaultPath')
});
ipcRenderer.on('open-file-paths',(event,data)=>{
    console.log(event);
    console.log(data);
});

The file open dialog works well enough, but I don’t know how to get the results. the ipcRenderer.on('open-file-paths',…) doesn’t get called, so that’s obviously not the right way to do it. I would like to get either the selected path(s) or a cancelled message.

How do I get the results for showOpenDialog in the render process?

Manngo
  • 14,066
  • 10
  • 88
  • 110

1 Answers1

3

OK, I think I’ve got it.

Thanks to an answer in ShowOpenDialog not working on recent versions of electron-js, I see that showOpenDialog now returns a promise, which means reworking the code in main.js. Here is a working solution:

//  main.js
    ipcMain.on('open-file',(event,data)=>{
        dialog.showOpenDialog(null, data).then(filePaths => {
            event.sender.send('open-file-paths', filePaths);
        });
    });

//  pager.js (render)
    ipcRenderer.send('open-file',{
        title: 'Title',
        defaultPath: localStorage.getItem('defaultPath')
    });
    ipcRenderer.on('open-file-paths',(event,data)=>{
        console.log(`Canceled? ${data.canceled}`);
        console.log(`File Paths: ${data.filePaths.join(';')`);
    });
Manngo
  • 14,066
  • 10
  • 88
  • 110