How to make a desktop app with html,css,js

Tawhid - Mar 16 '22 - - Dev Community

Did you know that you can make a desktop app with javascript?There's a js framework for this named electron.js .I was thinking of making a tutorial about this.Let's get into it.
Before starting,I want you to have
-basic knowledge of HTML,CSS,JS
-node.js installed in your system
-basic knowledge of node.js

Table Of Contents:

Explaination
Build
Paybacks of using Electron

Chapter 1

Structure of an Electron.js App

-Chromium: This is the component in the Electron.js structure that is responsible for creating and displaying web pages. Web content is displayed in Electron.js’s Renderer process (more on this later) and due to the Chromium environment, you have access to all browser APIs and development tools just like operating in a typical Google Chrome browser.
-Node.js: This is the component in the Electron.js structure that gives you access to system capabilities. Electron.js runs Node.js in its Main process (more on this later) giving you access to all that Node.js offers like interacting with the filesystem, operating system, etc. and more...
-Custom APIs: To enable developers to create common desktop experiences and work easily with native functionalities, Electron.js has an API of easy to use libraries that help you perform tasks like creating and showing a context menu, displaying desktop notifications, working with keyboard shortcuts, etc.

A running Electron.js app maintains two types of processes, the Main process, and one or more Renderer processes.The entry point is teh Main process.
The Main process is responsible for creating web pages. It does this by creating a new instance of the Electron.js BrowserWindow object. This creates a new web page that runs in its own Renderer process. The Main process can create more than one web page each running in its own Renderer process.

Typically, Electron.js applications boot up with a default web page which is the app’s startup screen. You can then create more screens if your application requires it.

Each Renderer process manages its own web page and is completely isolated from other Renderer processes and the Main process itself. Thus, if one Renderer process terminates, it does not affect another Renderer process. A Renderer process can also be terminated from the Main process by destroying its BrowserWindow instance.

Out of the box, the Renderer process only has access to browser APIs like the window and document objects, etc. This is because the Renderer process is simply a running Chromium browser instance. It can, however, be configured to have access to Node.js APIs such as process and require.

###Chapter 2

Build a Simple Electron.js Project
Now it’s time to get hands-on Electron.js experience! In this tutorial you will be creating a simple desktop application a task list. The goal is to create a desktop application from scratch and run it successfully.

To begin, run the following commands from your preferred parent directory to create a folder for the project, and then change directory into the new folder:

mkdir my-electron-app
cd my-electron-app
Enter fullscreen mode Exit fullscreen mode

Because an Electron.js app is, at heart, a Node.js application running web pages, you’ll need initialize the app and create a package.json file by running the following command:

npm init -y
Next, create the application home page by creating an index.html file at the root of the project folder and add the following code:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>My Electron App</title>
</head>

<body>
    <h1>Welcome to My Electron App</h1>
</body>

</html>
Enter fullscreen mode Exit fullscreen mode

The HTML code above creates a simple webpage with a title that reads “My Electron App” and an h1 tag in the body with the text “Welcome to My Electron App”.

At this point you have a basic Node.js application. The next step is to convert your app into a desktop application using Electron.js.

Start by installing the Electron.js library. Back in your command prompt, still in your project’s root directory, run the following command:

npm install --save-dev electron
Once the installation is complete, create a new file called main.js. This will be the entry point into the application: it’s the Main process script. This script will do the following:

Create a web page for the application home screen
Load the application home screen when the Electron.js app is booted up
Load the home screen when the app’s icon is clicked if the app’s windows are closed but the app is still running
In your new file, main.js, begin by importing the necessary packages and then creating a function whose job is to create a new web page for the application home screen:

//import from electron 
const { app, BrowserWindow } = require("electron");
const path = require("path");

//load the main window
const loadMainWindow = () => {
    const mainWindow = new BrowserWindow({
        width : 1200, //width of window
        height: 800, //height of window
        webPreferences: {
            nodeIntegration: true
        }
    });

load the `index.html` file
    mainWindow.loadFile(path.join(__dirname, "index.html"));
}
Enter fullscreen mode Exit fullscreen mode

In the code block above, app (the Electron.js application object) and BrowserWindow (the Electron.js module for creating and loading web pages) are imported from the Electron.js package. The path module is also imported, enabling you to work with the project directory.

After the imports, you create the loadMainWindow() function. This function uses the BrowserWindow object to create a new 1200px by 800px browser window that loads the index.html file from the project’s root.

Next, beneath the existing code, add a call to the loadMainWindow() function so that the function is invoked immediately after the app boots up:

app.on("ready", loadMainWindow);

The loadMainWindow() only gets called when the ready event is emitted on the app. The web page needs to wait for this event because some APIs can only be used after this event occurs.

The next step is to take care of an issue on some operating systems where the application still remains active even after all windows have been closed. This often occurs on non-MacOS platforms. To fix this, add the following below the existing code in main.js:

app.on("window-all-closed", () => {
  if (process.platform !== "darwin") {
    app.quit();
  }
});
Enter fullscreen mode Exit fullscreen mode

This code instructs the app to listen for the window-all-closed event, which is fired when all windows created by the Main process have been closed. It then checks if the platform is MacOS and if not, it explicitly quits the application, ending the Main process and thus terminating the application.

The final step in this file is to ensure that the application boots up when its icon is clicked in the operating system’s application dock when there are no windows open. To achieve this, add the following code at the end of the file:

app.on("activate", () => {
    if (BrowserWindow.getAllWindows().length === 0) {
        loadMainWindow();
    }
});
Enter fullscreen mode Exit fullscreen mode

This code listens for the activate event on the app. When the event is emitted, this code checks if there are any windows currently open that belong to the application. If not, the home screen is loaded by calling loadMainWindow().

That’s it for the main.js file.

Configure the Application
You’ll need to make some changes to your package.json file to ensure that it’s configured correctly to work with Electrion.js.

Open your package.json file. Change the value of the main key to main.js as shown below:

"main": "main.js",
Next, add a start script to the scripts section like below:

"scripts": {
    "start" : "electron .",
    "test": "echo \"Error: no test specified\" && exit 1"
 }
Enter fullscreen mode Exit fullscreen mode

Save and close the file. At this time, you can run your new Electron.js application with the following command:

npm start
This will boot up the application and load the home screen window.

Create a Simple Task List System
In order to learn some other features of Electrion.js, you will be creating a bare-bones task list system.

To begin, you’ll add some basic content to your app’s home screen.

Open the index.html file and add the Bootstrap library just below the meta tags in the head section as shown below:

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/css/bootstrap.min.css" integrity="sha384-TX8t27EcRE3e/ihU7zmQxVncDAy5uIKz4rEkgIXeMed4M0jlfIDPvg6uqKI2xXr2" crossorigin="anonymous">
    <title>My Electron App</title>
</head>
Enter fullscreen mode Exit fullscreen mode

Next, inside the body element, below the h1 tag, add the highlighted lines to create a two-column layout. The first column will contain the task list:

<body>
    <h1>Welcome to My Electron App</h1>
    <div class="container">
       <div class="row">
           <div class="col-md-6">
               <ul id="list" class="list-group">
                  <li class="list-group-item">Buy Groceries</li>
                  <li class="list-group-item">Cook Meal</li>
               </ul>
           </div>

           <div class="col-md-6">
           </div>
       </div>
    </div>
</body>
Enter fullscreen mode Exit fullscreen mode

If the app is currently running, close it by pressing Ctrl+Cin your command prompt and restart it by running npm start.

Add a New Item to the Task List
In your index.html file, add a form input and button element. The user will interact with these elements to add new items to the task list. To add these elements, copy and paste the highlighted lines into the second column of the two-column grid:

<body>
    <h1>Welcome to My Electron App</h1>
    <div class="container">
        <div class="row">
            <div class="col-md-6">
                <ul id="list" class="list-group">
                  <li class="list-group-item">Buy Groceries</li>
                  <li class="list-group-item">Cook Meal</li>
                </ul>
            </div>

            <div class="col-md-6">
                <input class="form-control" id="newTask" placeholder="Enter New Task" />
                <br />
                <button type="button" class="btn btn-primary" id="addTask">
                    Add Task
                </button>
            </div>
        </div>
    </div>
</body>
Enter fullscreen mode Exit fullscreen mode

Now, create a new JavaScript file called script.js at the root of the project and import it into the index.html file as shown below:

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/css/bootstrap.min.css" integrity="sha384-TX8t27EcRE3e/ihU7zmQxVncDAy5uIKz4rEkgIXeMed4M0jlfIDPvg6uqKI2xXr2" crossorigin="anonymous">
    <script src="script.js"></script>
    <title>My Electron App</title>
</head>
Enter fullscreen mode Exit fullscreen mode

Inside the script.js file, add the following code:

let list = document.getElementById("list");
let newTask = document.getElementById("newTask");

document.getElementById("addTask").addEventListener('click', () => {
    list.insertAdjacentHTML('beforeend', `<li class="list-group-item">${newTask.value}</li>`)
    newTask.value = '';
});
Enter fullscreen mode Exit fullscreen mode

In the code above, a click event handler is added to the button element you added in index.html. When the button is clicked, the value of the input field is inserted into a new <li> element, which is appended to the task list.

Now, quit the application and restart. Try adding a few new items by typing in the input field and clicking the Add Task button.

It works right?!THE POWERR OF FEELIN'

Conclusion
Electron.js is a game-changer in the world of application development as it gives web developers the ability to enter the native application development space with their existing set of skills.

Chapter 3

Paybacks
-High RAM consumption: Electron apps tend to use a minimum of 80 MB of RAM, with lightweight apps in the 130-250 MB range and monsters like Slack sometimes reaching multi-GB values.

-Large storage footprint: Shipping with a full Chromium runtime, you can expect most Electron apps to consume at least 150 MB of storage.

-Slow: Some Electron apps are definitely slow, but that can depend on many factors. Overuse of animations, for example, can substantially increase the CPU usage and thus make the app feel slower. Did you notice that most desktop apps that feel snappy don’t include any animation? Just because you can with Electron, doesn’t mean you should.

-Lack of native UI/UX: Electron renders webpages and not native controls. On one hand, that gives complete freedom to designers, but on the other, the app looks different from the “native” ones. Unsurprisingly, this complaint usually comes from macOS users, where a single “native” framework exists: Cocoa. Due to the fragmentation of GUI frameworks on other platforms (especially Windows), non-macOS users are usually more tolerant of apps not sharing the same look and feel.

-Worse security: Compared to the average website running on your web browser, Electron apps are incredibly more powerful (and dangerous) thanks to the NodeJS integration. If not properly configured, web pages running inside Electron can gain access to the entire system, which is particularly dangerous when displaying third-party websites. Luckily, it doesn’t have to be that way, as Electron provides Context Isolation to shield the renderer from NodeJS APIs. Moreover, some believe that the NPM ecosystem is less secure than other counterparts.
Buy me a coffee

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .