Building desktop applications with Electron - Native UI
This tutorial assumes you know how to install and set up electron-quick-start project. You can find the tutorial here.
The shell module in Electron allows you to access certain native elements like the file manager and default web browser.
We can load the shell module by creating new constant shell and requiring electron.shell.
const shell = require(‘electron’).shell
We will also load os module and assign it to the os constant. We use this module to get user’s home directory.
const os = require(‘os’)
Start by adding button with id of open-file-manager to the index.html file at the end of body tag. The text of button should be “Open file manager”. We are providing id because we will use it to reference element in JavaScript file.
<button id=”open-file-manager”>Open file manager</button>
Great, now let’s use our id from the button and define const fileManagerBtn . We can get a reference to element by using document.getElementById and specifying our button id.
const fileManagerBtn = document.getElementById(‘open-file-manager’)
And the last thing we need to do is to define new click event listener. Do this by calling fileManagerBtn.addEventListener and passing ‘click’ as a parameter and anonymous function with an event parameter.
Inside the function will call the shell.showItemInFolder and pass our os.homedir() as a parameter. This will open up the file manager and display all the items in our home directory.
fileManagerBtn.addEventListener(‘click’, function (event) {
shell.showItemInFolder(os.homedir())
})