Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Electron - Open Folder Dialog

I want the user to be able to pick a folder from the folder dialog box.
So far, I've tried following this tutorial unsuccessfully.
I got stuck on the part of

exports.selectDirectory = function () {
  // dialog.showOpenDialog as before
}

What do I need to do in order to retrieve the full path of the selected folder?
Thanks!

like image 255
avi12 Avatar asked Sep 03 '17 19:09

avi12


2 Answers

Dialog api is available in main process(https://electron.atom.io/docs/).

To create a dialog box you will have to tell your main process to do so by sending a message from renderer process.

Try this code:

// in your renderer process:-

const ipcRenderer = require('electron').ipcRenderer;

ipcRenderer.send('selectDirectory');


//in you main process:-

const electron = require('electron');

const ipcMain = electron.ipcMain;

const dialog = electron.dialog;

//hold the array of directory paths selected by user

let dir;

ipcMain.on('selectDirectory', function() {

    dir = dialog.showOpenDialog(mainWindow, {

        properties: ['openDirectory']

    });

});

Note: mainWindow here, it's the parent browserWindow which will hold the dialog box.

like image 188
Anil Kumar Avatar answered Nov 16 '22 02:11

Anil Kumar


You need to use electron remote

const {dialog} = require('electron'),
WIN = new BrowserWindow({width: 800, height: 600})

/*
//renderer.js - a renderer process
const {remote} = require('electron'),
dialog = remote.dialog,
WIN = remote.getCurrentWindow();
*/

let options = {
 // See place holder 1 in above image
 title : "Custom title bar", 

 // See place holder 2 in above image
 defaultPath : "D:\\electron-app",

 // See place holder 3 in above image
 buttonLabel : "Custom button",

 // See place holder 4 in above image
 filters :[
  {name: 'Images', extensions: ['jpg', 'png', 'gif']},
  {name: 'Movies', extensions: ['mkv', 'avi', 'mp4']},
  {name: 'Custom File Type', extensions: ['as']},
  {name: 'All Files', extensions: ['*']}
 ],
 properties: ['openFile','multiSelections']
}

//Synchronous
let filePaths = dialog.showOpenDialog(WIN, options)
console.log('filePaths)

//Or asynchronous - using callback
dialog.showOpenDialog(WIN, options, (filePaths) => {
 console.log(filePaths)
})
like image 22
Abhijith Darshan Avatar answered Nov 16 '22 02:11

Abhijith Darshan