How to get path of selected directory into renderer process

Viewed 685

I want to store in variable the path of local directory selected using dialog.showOpenDialog. I tried every tutorial and stack answer without any luck. Best part is that even the electron-api-demos solution isn't working (I am using one here) So, dialog opens, I can select a folder or a file - but nothing is send back to renderer process.

Here I am testing this with opening files but also no results. I am using jquery btw and elcetron v 12. Here is my code:

Renderer process:

$('.js_select_folder').on('click', (e) =>{
    ipcRenderer.send('open-folder')
    e.preventDefault();
})
    
ipcRenderer.on('selected-folder', (event, path) => {
    console.log('wtf',path)
    $('#info').text('Result :'+path)   
})

Main process:

ipcMain.on('open-folder',  (event) => {
    dialog.showOpenDialog({ properties:['openFile']}, (files) => {
        if(files){
            console.log(files)
            event.reply('selected-folder', files)
        }
    })
})

No trace of console.log(files) anywhere. Any ideas what I am doing wrong?

1 Answers

I figured it out:

renderer process:

$('.js_test').on('click', (e)=>{
    e.preventDefault();
    ipcRenderer.send('open-folder')
})

ipcRenderer.on('sel-dir', (event, path) => {
  const message = `This app is located at: ${path}`
    $('#info').text(message)   
})

main process:

ipcMain.on('open-folder', (event, arg) => {
  dialog.showOpenDialog({properties: ['openDirectory']}).then(result=>{
    event.sender.send('sel-dir', result.filePaths)
  })
})

So it is actually super simple as you can see but took me two days to figure it out. The result is that I get the path (or any data) back to renderer after choosing dir or file.

Regards, Mac.

Related