Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Creating a Hybrid Desktop Application Using Electron

0.00/5 (No votes)
8 Apr 2016 1  
A step by step guide to creating a simple hybrid desktop application using web development and Electron framework

Introduction

I spent the last couple of weeks looking for answers to simple questions. I have started to learn web development and I wanted to apply that knowledge to implement an application that works as a desktop app, so I came across Electron framework, which is a framework to create desktop applications from web applications or so called framework for desktop hybrid development. My goal was really simple, I wanted to create a running web application, build it into a hybrid desktop app and then distribute that application easily to my clients.

There are answers for all my questions on the Internet, but they were distributed in many places and most of them assume that you have an experience dealing with node.js, grunt tasks and other techs. After gaining the required knowledge to apply my idea, now I want to share that knowledge and put all those distributed pieces in one place so any one can find them easily.

This tutorial is going to cover three simple areas:

  1. How to create a simple desktop hybrid application using your knowledge in web development
  2. How to build that application to be executed in different operating systems
  3. How to pack and distribute it as an installable product

But What is Electron?

Electron is an open source framework by Github that lets you simply build a desktop application using your web development knowledge. It provides many of the features provided by native applications like installers, auto update, crash reporting and notifications. You can simply think of Electron as a wrapper for your web application, it creates executables that run on different operating systems and provide ways to communicate with the underlying OS. This way, you will be in no need for creating a separate application for each operating system.

Using the Code

Create a Simple Electron App

You need to know that the simplest Hybrid desktop application using Electron consists of three files:

  • Index.Html which is "an" HTML document contains the web content that you want to show
  • Main.Js which is a JavaScript file that would start the application and create a container in the operating system to render the HTML file
  • Package.json is a configuration file that contains the filename which your application should start from and the dependencies list that your application relies on

You can install a sample application rather than creating those files yourself from https://github.com/atom/electron-quick-start.

WARNING: In this tutorial, you will deal with a lot of command line commands, I know it seems frustrating sometimes, but you will find those commands which we need to be so simple and easy to execute.

The most important tool we need before heading forward is a tool called Node.js which you can download from https://nodejs.org/en/download/. That tool gives us access to many of the JavaScript libraries that we need and that would help us in simplifying our implementation process.

So after downloading that simple app, you can adjust the Index.html file to look a little bit like this:

Index.html

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <title>First Hybrid app!</title>
  </head>
  <body>
    <h1>Hello From Electron Side!</h1>   
  </body>
</html>

If you decided not to download the sample code and wanted to create the files from scratch, then they should look like this:

Main.js

'use strict';

const electron = require('electron');
// Module to control application life.
const app = electron.app;
// Module to create native browser window.
const BrowserWindow = electron.BrowserWindow;

// Keep a global reference of the window object, if you don't, the window will
// be closed automatically when the JavaScript object is garbage collected.
let mainWindow;

function createWindow () {
  // Create the browser window.
  mainWindow = new BrowserWindow({width: 800, height: 600});

  // and load the index.html of the app.
  mainWindow.loadURL('file://' + __dirname + '/index.html');

  // Open the DevTools.
  mainWindow.webContents.openDevTools();

  // Emitted when the window is closed.
  mainWindow.on('closed', function() {
    // Dereference the window object, usually you would store windows
    // in an array if your app supports multi windows, this is the time
    // when you should delete the corresponding element.
    mainWindow = null;
  });
}

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
app.on('ready', createWindow);

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

app.on('activate', function () {
  // On OS X 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 (mainWindow === null) {
    createWindow();
  }
});

package.json

{
  "name": "electron-quick-start",
  "version": "1.0.0",
  "description": "A minimal Electron application",
  "main": "main.js",
  "scripts": {
    "start": "electron main.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/atom/electron-quick-start.git"
  },
  "keywords": [
    "Electron",
    "quick",
    "start",
    "tutorial"
  ],
  "author": "GitHub",
  "license": "CC0-1.0",
  "bugs": {
    "url": "https://github.com/atom/electron-quick-start/issues"
  },
  "homepage": "https://github.com/atom/electron-quick-start#readme",
  "devDependencies": {
    "electron-prebuilt": "^0.36.0"
  }
}

Now we have created the simplest electron app ever, now we need to build it and test it on our operating system. For this tutorial, I will be using Windows OS but I believe that this process is the same for Linux and for OS X.

Building and Running the Application

Let the fun begin!

If you installed the prebuilt sample project, then you can ignore this step and head directly to the next one, if not, then we need to install the dependencies which are listed in our configuration file and to do that, open your command line and change the current directory to the directory which has those three files inside, and let’s call this folder the root folder or root directory and we will refer to it using that in the remainder of this article, and then execute this command:

npm install

This is going to install the dependencies listed in your configuration document.

Now, we are going to install one of those prebuilt packages that we referred to when we installed node.js, the library we are going to install called electron-packager and it is going to take our three files and wrap them into an OS executable file. To install the package, execute the next command in your command line tool:

npm install electron-packager -g

-g here means that this library will be installed globally in the machine and we can reuse it later.

Now open your package.json file and add this script to your scripts section:

"build": "electron-packager . myapp --platform=win32 --arch=x64 version=0.36.12"

The scripts section would now look like this:

"scripts": {
    "start": "electron main.js",
    "build": "electron-packager . --platform=win32 --arch=x64"
  }

Then to run this script, from your command line tool, execute:

npm run build

This would execute the script and package your files into executable file for windows x64. You can find the executable app in the new created folder in your root directory called version=0.36.12-win32-x64 which obviously named according to our setting in the build script. You can find the available options for the platform and the arch at https://www.npmjs.com/package/electron-packager.

Now we have a web application running as a desktop app. From this point on, you can just manipulate your HTML file or JS file without executing the build script again. You can find your source files in the new directory (root folder -> version=0.36.12-win32-x64 -> resources-> app) folder and you can modify them and run the executable directly to see the changes.

Create an Installer to Your Application

For sure, you don’t want to copy all those files and send them to your friends or clients so let’s make one executable file that you can distribute to be used in other machines. To create the installer, we need a library called “grunt electron installer” along with other two libraries that library depends on and we need also to add a new configuration document to our root folder.

To add the libraries, execute these commands sequentially:

npm install grunt-cli -g
npm install grunt
npm install grunt-electron-installer

And in your root folder, add a new text file and rename it to be gruntfile.js. The content of this file would look like this:

module.exports = function (grunt) {
  'use strict';
 
  grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
    'create-windows-installer': {
  x64: {
    appDirectory: 'version=0.36.12-win32-x64',
    outputDirectory: 'build/',
    authors: 'Banan IT.',
    exe: 'BSc.exe',
    noMsi:true
  }
}
});

grunt.loadNpmTasks('grunt-electron-installer');
}

That simple code is a JavaScript function that would run a task for us to create the installer. Note that the app directory refers to the folder which contains our executable file and the output directory refers to a folder that would contain our installer.

To create the installer, execute this command:

grunt create-windows-installer

If the command executed without errors, you can now find your installer ready in the output directory we listed in the gruntfile.js.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here