‹ Learn to code in just two weeks. Apply to our cohort program today. ›

Build an Electron App

Build a simple native desktop app with HTML, CSS and JS!

Web Development

Node.Js

Beginner

June 14, 2020

views



Interested in this project?

Continue Learning

Build a Desktop App with HTML, CSS, and JavaScript!

You're probably going like, "Say what now?", but yes, it's possible. All thanks to Electron.js. Electron is a package developed by GitHub that allows you to make native apps with web technologies like HTML, CSS and JS. For this to work, you're going to have to have Node.js. To check if you have all the required dependencies, run node -v and npm -v in your terminal. If either of them come up looking like this: 'node' is not recognized as an internal or external command, operable program or batch file., then download Node.js using the link above. Then, in command prompt, run npm install --save-dev electron to install Electron.

Setup

The structure of our app is going to look a bit different to most Enlight tutorial apps. Make a folder named electron-app, and open command prompt. Open the folder by typing cd and then the directory of the folder. It should look something like this: cd C:\Users\me\Desktop\electron-app. Once you are inside the folder, run the command npm init. It will ask you for the name of the app. By default this is the name of the folder. You can leave everything blank, except for main, which you need to change to main.js, and test, which you need to change to electron . The electron is telling Node to run the command electron and the . is telling Node to do that right here for all the files in this folder. Once you are finished, open the folder in your favorite editor, such as VSCode or Atom.

Making the app

Create a file called index.js, and we'll start by importing the package as constant (const), a variable that cannot be reassigned. Then, we'll create a function called createWindow that will make our electron app pop up when we call it.

// index.js
const { app, BrowserWindow } = require('electron')

function createWindow () {
    // Create the browser window.
    const win = new BrowserWindow({
        width: 800,
        height: 600,
        webPreferences: {
            nodeIntegration: true
        }
    })

    // and load the index.html of the app.
    win.loadFile('index.html')

    // Open the DevTools.
    win.webContents.openDevTools()
}

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.whenReady().then(createWindow)

First, we imported the app and BrowserWindow modules to control the app for us from the electron framework. In our function createWindow, we specified the details of the window that actually appears such as the dimensions. In the last section of the function we called .loadFile and .openDevTools functions on our application window to select the html file we want it to display inside and to open the developer tools console. Finally, we call the createWindow function we just wrote when the app has fully loaded.

Now that our app is open, we also need to make sure it properly quits when we want it too as well. Here are some settings to add so that the app behaves properly on macOS.

// Quit when all windows are closed, except on macOS. There, it's common
// for applications and their menu bar to stay active until the user quits
// explicitly with Cmd + Q.
app.on('window-all-closed', () => {
    if (process.platform !== 'darwin') {
        app.quit()
    }
})

app.on('activate', () => {
    // On macOS it's common to re-create a window in the app when the
    // dock icon is clicked and there are no other windows open.
    if (BrowserWindow.getAllWindows().length === 0) {
        createWindow()
    }
})

Great, the hardest part is out of the way! Now we can add our HTML into index.html. Create this file in your project folder and insert the markup below:

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>electron-app</title>
</head>
<body>
    <h1>This app is built with HTML!</h1>
    <h3>And it's not witchcraft! It's Electron!</h3>
</body>
</html>

Now you can open your command prompt in the project folder and enter the commandnpm test. You should see a window on your desktop like this: electron app

...So now what?

You have just built a desktop application using Electron! That's great and all, but what can you do with it? One idea is to integrate one of any of the other projects on Enlight into this app. In my case, I would love to have my to-do list as a desktop app. Let's pull the source code from the to-do list tutorial and put it in our markup, style, and script! Let's create two new files, app.js and style.css for the style and script of the to-do list. We'll add the necessary HTML to the already existing index.html file! If you're interested in how this to-do list actually works under the hood, go through that tutorial first! For now though, have a look at the source code and write your files in a similar way, like this:

// app.js
function  newItem() {
    var  item  =  document.getElementById('input').value;
    var  ul  =  document.getElementById("list");
    var  li  =  document.createElement('li');

    li.appendChild(document.createTextNode("- "+item));
    ul.appendChild(li);
    document.getElementById('input').value="";
    li.onclick  =  removeItem;
}

document.body.onkeyup  =  function(e){
    if(e.keyCode  ==  13){
    newItem();
    }
}

function  removeItem(e) {
    e.target.parentElement.removeChild(e.target);
}

Don't remove the index.js file, you still need that for the app to acually start up. The app.js script is the portion that makes the to-do list itself run. Next, we do the style.

/* style.css */
html {
    font-family: "Avenir Next", Helevetica, sans-serif;
    text-align: center;
}
  
body {
    max-width: 500px;
    margin: 0  auto;
}
  
input {
    padding-top: 30px;
    width: 500px;
    height: 60px;
    font-size: 40px;
    border: 0;
}

input:focus {
    outline:none;
} 

li {
    text-align: left;
    font-size: 40px;
    list-style: none;
    margin: 0;
}

li:hover {
    text-decoration: line-through;
}

Finally, we update the head of our index and replace the body of the HTML. It's also important to inject the script for app.js using the <script> tag!

<!-- index.html -->
<!doctype html>
<html  lang="en">
    <head>
        <meta  charset="UTF-8">
        <meta  name="viewport"
        content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
        <meta  http-equiv="X-UA-Compatible"  content="ie=edge">
        <link  rel="stylesheet"  href="style.css" />
        <title>My To Do List App</title>
    </head>
    <body>
        <input  id="input"  placeholder="What needs to be done?">
        <ul  id="list"></ul>
    </body>
    <script  src="app.js"></script>
</html>

Fire up your app again with npm test and check it out! If this worked for you, you now have the power of a desktop app that provides a home for your to-do list!

Conclusion

To take this project a step further, can you figure out how to enable storage for your to-dos? Additionally, what about creating a shortcut to the app on your desktop? Here's a hint: check out a little package called Squirrel. Good luck!

Comments (0)