You can initiate a file system open dialog
from a Renderer Process
(a browser window).
On your Main Process
, you are listening to the Renderer Process
, in case of open-file-dialog
command is sent from the Renderer Process
, the Main Process
will display an Open File Dialog per the Operating System (As demonstrated below, an ['openFile']
property is being sent, and you can also use ['openDirectory']
for Open Directory dialog, or both of them) and will send back the selected file\path to the Renderer Process
.
Renderer process
//Adding an event listener to an html button which will send open-file-dialog to the main process
const ipc = require('electron').ipcRenderer
const selectDirBtn = document.getElementById('select-file')
selectDirBtn.addEventListener('click', function (event) {
ipc.send('open-file-dialog')
});
//Getting back the information after selecting the file
ipc.on('selected-file', function (event, path) {
//do what you want with the path/file selected, for example:
document.getElementById('selected-file').innerHTML = `You selected: ${path}`
});
Main Process
//listen to an open-file-dialog command and sending back selected information
const ipc = require('electron').ipcMain
const dialog = require('electron').dialog
ipc.on('open-file-dialog', function (event) {
dialog.showOpenDialog({
properties: ['openFile']
}, function (files) {
if (files) event.sender.send('selected-file', files)
})
})