Table of Contents
Over in the [first part](/electron/intro-to-electron-setup) of this introduction to Electron.js, we just got Electron setup with our bundling scripts and a local window. With the foundations out of the way, we can get started with the more interesting functionality of our app.
Passing Data Between Client and Server
Since we're not setup with a database yet, the todo functionality is almost the same as any vanilla JavaScript todo app. The only difference being we'll first use ipcRenderer.send to send an event to our server with our data, which we can listen for with ipcMain.on, then do whatever we need to with the data (like save it to our database), and send it back to the client to be rendered if successful.
[label script.js]
const electron = require('electron')
const { ipcRenderer } = electron
const form = document.querySelector('form')
const item = document.querySelector('input')
const list = document.querySelector('ul')
// Render Items to Screen
const render = item => {
const li = document.createElement('li')
li.innerHTML = item
list.appendChild(li)
}
// Get All Items After Starting
window.addEventListener('load', () => ipcRenderer.send('loadAll'))
ipcRenderer.on('loaded', (e, items) => items.forEach(item => render(item.item)))
// Send Item to the server and clear the form
form.addEventListener('submit', e => {
e.preventDefault()
ipcRenderer.send('addItem', { item: item.value })
form.reset()
})
Next we just need to start a new database with Datastore and use some mongoose-like methods when we catch our events from the client.
Instead of a method on ipcMain, as you may expect, we need to use webcontents.send on the window we want it applied to. Later this will also allow us to send events from our menu without destructuring anything from electron.
The main methods that we need just take an object with the properties you want the return item to match, and a callback function for when it's complete.
insertTakes the new item as an object and adds it to the database.
removeTakes the query, and object of options, and removes from the database.
findTakes the query and returns the objects.
updateTakes the query and an object of properties you want updated.
[label app.js]
const db = new Datastore({
filename: './items.db',
autoload: true
})
// Get all items from db and send them to the client
ipcMain.on('loadAll', () => db.find({}, (err, items) => mainWindow.webContents.send('loaded', items)))
// Saves item and returns it to client
ipcMain.on('addItem', (e, item) => {
db.insert(item, err => {
if (err) throw new Error(err)
})
mainWindow.webContents.send('added', item)
})
Menu Bar
Now we can start adding some more interesting functionality into our menu bar. For every object in our array we have a few options to customize it.
labelSet the name shown on the menu bar
submenuSets and array of objects as a sub directory, these can go on infinitely.
clickSets an onClick handler, takes in itself and the current focused window.
acceleratorSets any keyboard shortcuts, we can useprocess.platformto check what OS is being used, since Mac and Windows have a few different keys.
typeSet menu item as one of electrons preset formats;normal,separator,checkbox, andradio.
Along with our file menu, we're going to add the option to toggle the dev tools to help debug our application.
[label MenuBar.js]
const menuBar = [
{
label: 'file',
submenu: [
{
label: 'Clear All',
accelerator: process.platform == 'darwin' ? 'Command+C' : 'Ctrl+C',
click(item, currentWindow) { currentWindow.webContents.send('clearAll') }
}
]
}, {
label: 'DevTools',
accelerator: process.platform == 'darwin' ? 'Command+I' : 'Ctrl+I',
click(item, mainWindow) { mainWindow.toggleDevTools() }
}
]
With the cleared event being sent, we can clear our ul.
[label script.js]
// Catches ClearAll from menu, sends the event to server to clear the db.
ipcRenderer.on('clearAll', () => ipcRenderer.send('clearAll'))
ipcRenderer.on('cleared', () => list.innerHTML = '')
[label app.js]
// Clears database and send event to client if successful
ipcMain.on('clearAll', () => {
// Without multi being set to true only the first matching item with be removed.
db.remove({}, { multi: true }, (err) => {
if (err) throw new Error(err)
mainWindow.webContents.send('cleared')
})
})
Bundling
Before we can bundle our new app we need some icons to go with it, but they need to be in the right formats for their operating system. icns for Mac and Linux and ico for Windows. I recommend using Cloud Convert to do this.
When they're all in the correct locations you can just run their script from our package.json file and a new release-builds folder should be created. In your OS's folder you can find your new application ready to run natively on your machine.
$ npm run package-mac
$ npm run package-win
$ npm run package-linux
Conclusion
While this may have been a bit of a lengthy process, I hope that you found this helpful in understanding the fundamentals of building your own desktop apps using Electron. You can find the full repo for this example github.com.