DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workkloads.

Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Decoding the Merits of MEAN Tech Stack for Your Organization
  • Difference Between Bootstrap and AngularJS in 2022
  • How I Used Swift Script in Electron Browser Natively
  • Node.js: Architectural Gems and Best Practices for Developers to Excel

Trending

  • Transforming AI-Driven Data Analytics with DeepSeek: A New Era of Intelligent Insights
  • How to Convert XLS to XLSX in Java
  • Microsoft Azure Synapse Analytics: Scaling Hurdles and Limitations
  • It’s Not About Control — It’s About Collaboration Between Architecture and Security
  1. DZone
  2. Coding
  3. Frameworks
  4. Electron Js + jQuery + Bootstrap - Dev to Build

Electron Js + jQuery + Bootstrap - Dev to Build

By 
Venkatesh Rajendran user avatar
Venkatesh Rajendran
DZone Core CORE ·
Oct. 13, 20 · Tutorial
Likes (6)
Comment
Save
Tweet
Share
24.2K Views

Join the DZone community and get the full member experience.

Join For Free

Whenever we need software, we go to a website and download a package, and after a couple of clicks, the software will be installed on your PC. As a web developer, you may not have experience in building a Desktop application.

In this article, we look into "how can we build a Desktop application with web technologies". If you Google the above-quoted text, the result will be Electron JS.

What Is Electron.js? 

Electron's docs says, "Electron JS is a runtime framework that allows the user to create desktop-suite applications with HTML5, CSS, and JavaScript".

Here, you might be asking what is compiling our JS code we write. It combines the Chromium rendering engine and the Node. js runtime. So, to build an Electron application, we need basic knowledge of Node.js as a prerequisite. And I assume here that you are familiar with JS. I think, this fair enough for the introduction. Let's move on to the topic.

Prerequisites

* NodeJs & NPM : latest
* A code editor

Electron Forge helps us to create the electron app in an easy way. To understand the basics, let's go in the traditional way.

Create a folder wherever you want in your pc. Open cmd, and run npm init. Please enter the details of the project for the generated package.json. Now, all we need is Electron JS. Electron JS is a dev dependency, and it should be installed globally. Install it with the help of npm install -g electron --only=dev. Once installed, the package.json should have Electron as a devDependency. (If not please add it manually.)

JSON
xxxxxxxxxx
1
 
1
"devDependencies": {
2
    "electron": "^10.1.3"
3
  }


In Electron JS, there are two processes. One is the main process and the other is the renderer process. Let's check what docs say about Main and Renderer processes.

Main Process

In Electron, the process that runs package.json's main script is called the main process. The script that runs in the main process can display a GUI by creating web pages. An Electron app always has one main process, but never more.  

Renderer Process

Since Electron uses Chromium for displaying web pages, Chromium's multi-process architecture is also used. Each web page in Electron runs in its own process, which is called the renderer process.

To communicate between the main and renderer processes, Electron provides us the support called Inter-Process Communication. 

ipcMain: It listens to the events from the renderer processes.

JavaScript
 
xxxxxxxxxx
1
 
1
// In main process.
2
const { ipcMain } = require('electron')
3
ipcMain.on('synchronous-message', (event, arg) => {
4
  console.log(arg) // prints "ping"
5
  event.returnValue = 'pong'
6
})


ipcRenderer: Communicates asynchronously from a renderer process to the main process.

JavaScript
 
xxxxxxxxxx
1
 
1
// In renderer process (web page).
2
const { ipcRenderer } = require('electron')
3
console.log(ipcRenderer.sendSync('synchronous-message', 'ping')) // prints "pong"


I believe this is the right time to get our hands dirty. Create a main.js file in the project directory, and it should be mentioned in package.json's main property. If it's not added in the process of npm init, please add it manually.

JavaScript
xxxxxxxxxx
1
42
 
1
const { app, BrowserWindow, ipcMain} = require('electron')
2
const url = require('url')
3
const path = require('path')
4

          
5
function createWindow () {
6
  // Create the browser window.
7
  const win = new BrowserWindow({
8
    width: 800,
9
    height: 600,
10
    webPreferences: {
11
      nodeIntegration: true
12
    }
13
  })
14

          
15
  // and load the index.html of the app.
16
  win.loadURL(url.format ({
17
    pathname: path.join(__dirname, 'src/index.html'),
18
    protocol: 'file:',
19
    slashes: true
20
  }))
21

          
22
  // Open the DevTools.
23
  win.webContents.openDevTools()
24

          
25
}
26

          
27
// Once our app is ready, we create an window and load index.html
28
app.whenReady().then(createWindow)
29

          
30
// on mac, processes will be running until user close it with cmd + q
31
app.on('window-all-closed', () => {
32
  if (process.platform !== 'darwin') {
33
    app.quit()
34
  }
35
})
36

          
37
// When app is active, At least one window should be open.
38
app.on('activate', () => {
39
  if (BrowserWindow.getAllWindows().length === 0) {
40
    createWindow()
41
  }
42
})


If you notice the win.loadURL(), we load index.js, which lies in the src folder. Let's create an src folder inside our app dir. Here, we create index.html, index.js, and index.scss.
Before we create them, let's take a step back and look at what we need.

We need to create a UI with a form that gets the date from the User and submits. So, We need jQuery, bootstrap, and a data-picker (js-datepicker).

npm install --save bootstrap 
npm install --save jquery 
npm install --save js-datepicker 

Create index.js, and require all the packages you need.

JavaScript
xxxxxxxxxx
1
20
 
1
let $ = jQuery = require('jquery');
2
const datepicker = require('js-datepicker')
3

          
4
let date = datepicker("#mydate",{
5
    formatter: (input, date, instance) => {
6
      input.value = getFormattedDate(date)
7
    }
8
})
9

          
10
$("form").submit(e=>{
11
    e.preventDefault();
12
    let date = $("#mydate").val();
13
    console.log("picked date", date)
14
})
15

          
16
function getFormattedDate(date) {
17
    return ((date.getMonth() > 8) ? (date.getMonth() + 1) : ('0' + (date.getMonth() + 1))) 
18
            + '-' + ((date.getDate() > 9) ? date.getDate() : ('0' + date.getDate())) 
19
            + '-' + date.getFullYear()
20
  }


Now, create an index.html and load index.js into it.

HTML
xxxxxxxxxx
1
28
 
1
<!DOCTYPE html>
2
<html lang="en">
3
<head>
4
    <meta charset="UTF-8">
5
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
6
    <meta http-equiv="Content-Security-Policy" content="script-src 'self' 'unsafe-inline';" />
7
    <!-- <link rel="stylesheet" href="./bootstrap.min.css"> -->
8
  <!--If import scss is not working please try adding bootsrap manually from node modules-->
9
    <link rel="stylesheet" href="./index.scss">
10
    <link rel="stylesheet" href="../node_modules/js-datepicker/dist/datepicker.min.css">
11
    <title>Dowload File</title>
12
</head>
13
<body>
14
    <div class="center">
15
        <h2>Dowload File</h2>
16
        <form>
17
            <div class="form-group">
18
                <label for="mydate">Date :</label>
19
                <div style="position:relative">
20
                    <input type="text" id="mydate" class="form-control" data-date-format="dd/mm/yyyy" placeholder="Select a Date">
21
                </div> 
22
            </div>    
23
            <button type="submit" class="btn btn-primary">Submit</button>
24
        </form>
25
    </div>
26
    
27
</body>
28
</html>


index.scss

SCSS
xxxxxxxxxx
1
13
 
1
@import "~bootstrap/scss/bootstrap";
2

          
3
body{
4
    background-color: #eee;
5
    margin: auto;
6
}
7
.center {
8
    margin: auto;
9
    margin-top: 25px;
10
    width: 50%;
11
    border-radius: 25px;
12
    padding: 10px;
13
}


In order to send the selected date to the main process, we have to require ipcMain and ipcRenderer in main.js and index.js respectively.

JavaScript
xxxxxxxxxx
1
20
 
1
//// Modification in index.js /////
2

          
3
// require ipcRenderer in index.js
4
const {ipcRenderer} = require('electron')
5

          
6
// modify form submit listener
7
$("form").submit(e=>{
8
    e.preventDefault();
9
    let date = $("#mydate").val();
10
    console.log("picked date", date)
11
    ipcRenderer.send("object-date", date);
12
})
13

          
14

          
15
/// modifications in main.js ///
16
// ipcMain is already required in main.js
17
// listener to pick the date
18
ipcMain.on("object-date",(e, date)=>{
19
  console.log("selected date", date);
20
})


To run the app, we need to add script configuration in our package.json. Please add this in your package json.

JSON
xxxxxxxxxx
1
 
1
"scripts": {
2
    "start": "electron ."
3
  }


That's all. It's time to run our application. Open your cmd and cd to project dir. Then, run npm run start. Now, we have our standalone app running.

How to Build as an .exe File

In order to build the app we created, we need to add another dev dependency called electron builder and script configurations. Run npm install electron-builder --only=dev and change your package.json's script:

JSON
xxxxxxxxxx
1
22
 
1
{
2
  .......
3
    
4
  "main": "main.js",
5
  "scripts": {
6
    "start": "electron .",
7
    "dist": "electron-builder"
8
  },
9
  
10
  .......
11
// now your dependencies will look like this. 
12
    
13
  "dependencies": {
14
    "dotenv": "^8.2.0",
15
    "jquery": "^3.5.1",
16
    "js-datepicker": "^5.16.0"
17
  },
18
  "devDependencies": {
19
    "electron": "^10.1.3",
20
    "electron-builder": "^22.8.1"
21
  }
22
}


Also, we need to write the build configuration in package.json:

JSON
x
23
 
1
{
2
  ........
3
  
4
    "build": {
5
    "appId": "app-name",
6
    "win": {
7
      "target": [
8
        "nsis"
9
      ],
10
      "icon": "src/icon/win.ico",
11
      "requestedExecutionLevel": "requireAdministrator"
12
    },
13
    "nsis": {
14
      "installerIcon": "src/icon/win.ico",
15
      "uninstallerIcon": "src/icon/win.ico",
16
      "uninstallDisplayName": "downloadClient",
17
      "license": "license.txt",
18
      "oneClick": false,
19
      "allowToChangeInstallationDirectory": true
20
    }
21
  
22
  ........
23
}


I have kept the icon in scr/icon/. To check the build configurations of other OSs, please check the docs here.

Now, run npm run dist. In a couple of minutes, you should be having your software ready in the dist folder.

That's all. We have the software ready to install. Happy coding. For complete code implementation, please visit my git repo.

Electron (software framework) Build (game engine) dev Bootstrap (front-end framework) JQuery app application JavaScript JSON

Opinions expressed by DZone contributors are their own.

Related

  • Decoding the Merits of MEAN Tech Stack for Your Organization
  • Difference Between Bootstrap and AngularJS in 2022
  • How I Used Swift Script in Electron Browser Natively
  • Node.js: Architectural Gems and Best Practices for Developers to Excel

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!