</> Michael Burrows

Build a desktop app using HTML/CSS/JS & Electron

Last modified on September 28th 2020 GitHub [Source]

If you know how to build a website you can build desktop app’s with the Electron framework.

As an introduction to the framework we’ll create a simple desktop clock application.

Electron desktop clock app

Before getting started it’s recommended to have a current version of node.js installed.

Ok, first let’s create the folder/file structure required for this project:

electron-test/ ├─ package.json ├─ index.js ├─ index.html ├─ script.js ├─ style.css

package.json

This file Indicates which command to run when we start the application:

{ "name": "electron-test", "main": "index.js", "scripts": { "start": "electron ." } }

Note: Don’t use "name": "electron" or the Electron installation will fail.

Install Electron

Open up a new terminal window in the project folder and then run the install:

npm install --save-dev electron

This downloads all the required node modules and adds the dev dependency to our package.json.

index.js

This file is used to create windows and handle system events.

For our clock app we’ll create a small (190×80) fixed size browser window:

const { app, BrowserWindow } = require("electron"); app.whenReady().then(createWindow); function createWindow() { const win = new BrowserWindow({ width: 190, height: 80, resizable: false, }); win.loadFile("index.html"); }

index.html

Very basic HTML file that loads the CSS and JS for the the clock functionality:

<!DOCTYPE html> <html> <head> <meta charset="UTF-8" /> <title>Clock App</title> <link rel="stylesheet" href="style.css" /> </head> <body> <script src="script.js"></script> </body> </html>

script.js

Fetch’s the current time and updates it each second (1000 milliseconds) in the index.html.

function getTime() { time = new Date().toLocaleTimeString(); document.body.innerHTML = time; } setInterval(getTime, 1000);

style.css

Lastly the CSS to improve the appearance of our clock:

body { font-family: monospace; font-size: 32px; background-color: black; color: greenyellow; text-align: center; }

The monospace font prevents the clocks position shifting when the numbers change.

Start the application

We can now start our application by running the following command:

npm start