Get Started with Writing Desktop Apps with Electron

Image for post
Image for post
Photo by bruce mars on Unsplash

Electron is a framework that lets us create cross-platform desktop apps.

The apps are created by creating web apps that are wrapped with a wrapper.

In this article, we’ll look at how to create our first Electron app.

Getting Started

We’ve to use a recent version of Node.js to create our desktop app.

First, we install Electron by running:

To create the app, we create a project folder and run npm init --yes to create a package.json file.

Then we add the main.js to as the value of main .

This defines the entry point of our app.

The whole package.json file would look something like:

The start script just runs electron to run the main.js file.

Then in our main.js , we write:

We load the index.html file in an 800x600 window.

The BrowserWindow constructor creates the browser window.

webPreferences is a property with web page features.

nodeIntegration lets us set whether Node integration is enabled.

window.loadFile loads the HTML file we want to display.

app.whenReady().then(createWindow) runs the code to draw the window when the app is ready.

In index.html , we write:

to load something.

We can use the process.versions object to get data about the Node, Chrome, and Electron versions.

We can add more code to it to handle window closing and re-create the window from the Dock in macOS.

To do that, we write:

We add the window-all-closed event handler to quit the app when process.platform isn’t 'darwin' .

'darwin' is macOS.

So the handler would quit the app if all windows are closed on any platform other than macOS.

The 2nd handler handles the acrivate event.

We can use this to create new windows from when the dock icon is clicked on macOS.

When there’re no open windows, then we call createWindow to open a new window.

BrowserWindow.getAllWindows().length gets all the windows of our app.

We can start our app by running npm start .

Then we should see a window displayed:

Image for post
Image for post

Conclusion

We can create a simple electron app by installing the electron package and then create a JavaScript and HTML file.

Written by

Web developer. Subscribe to my email list now at http://jauyeung.net/subscribe/. Email me at hohanga@gmail.com

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store