Hello World Electron!

Tosin Onikute
11 min readJul 24, 2019

--

Beginner Introduction to desktop applications using Electron

Creating desktop apps with JS would either be done on Electron or NW.Js Both tools offer same set of features, first I would talk about comparison of each.

Electron is an open-source framework developed and maintained by GitHub. Electron allows for the development of desktop GUI applications using front and back end components originally developed for web applications: Node.js runtime for the backend and Chromium for the frontend.

While NW.js is a framework for building desktop applications with HTML, CSS, and JavaScript. It was created by Roger Wang at Intel’s Open Source Technology Center in China, and worked by combining the Node.js programming framework with Chromium’s (then) browser engine — Webkit, hence the original name Node Webkit.

We can clearly say both uses the power of Node.

What Is Node?

Node.js was initially released in 2009 as an open source project, enabling developers to create server-side applications using JavaScript

Read more about Node: https://nodejs.org/en/about/

lets do a quick comparison of both Electron and NW.js

First Comparison, entry point.

In Nw.Js the entry point is a web page or JS script, you can specify an html or JS file in a package.json.

In Electron, the entry point is a JS script, you have to manually create a browser window & load an HTML file using Electrons api.

Second Comparison, NodeJS integration.

In NW.js, the NodeJS integration in web pages requires patching Chromium to work, while in Electron a different and more easier approach is used which avoids hacking Chromium.

Third Comparison, the Build system.

Electron uses libchromiumcontent to avoid the complexity of building all of Chromium, libchromiumcontent is a Shared library build of Chromium’s Content module and all of its dependencies, you can also call it a web renderer that can build a stand alone shared file with all dependencies.

In case you are wondering what Chromium is, Chromium is an open-source browser project that forms the basis for the Chrome web browser. But let’s take a little deeper look at what that means.

It was first introduced by Google back in 2008, Both Chrome browser & Chromium source code was released, Chrome was based as an open-source project. That open-source code is maintained by the Chromium Project, while Chrome itself is maintained by Google.

What is included with Electron includes the Chromium Content Module (CCM) which is the core code that makes a web browser what it is. It includes the Blink rendering engine and its own V8 JavaScript engine. The CCM will handle retrieving and rendering HTML, loading and parsing CSS, and executing JavaScript as well.

You can read more about Chromium here: https://en.wikipedia.org/wiki/Chromium_(web_browser)

Also note that you do not need a sophisticated machine to build Electron.

So now that we’ve talked about a general overview of creating desktop applications, lets go straight into using Electron & It’s Core advantages

What Do I Need to Know to use Electron?

Unlike traditional desktop development, the only skills you need to have to develop with Electron are a good understanding of HTML, CSS, and JavaScript, and a touch of Node. An Intermediate experience with Node is a great advantage.

What advantages does Electron offer?

Electron applications are just like any other desktop application as they are installed locally on the user’s machine.They can be launched directly from the Windows taskbar or from the OSX Dock.

Electron operates in looser security than your browser

Yeah, you read that correctly, this can be an advantage depending on the context of the scenario. If you have worked with an external API, then you are probably familiar with the restrictions from Cross Origin Resource Sharing issues, or establishing proxies in order to allow our web application to work correctly.

Since a user has consented to install and run an Electron application, a degree of trust is assumed between the user and application & this allowed the Electron freedom to be much more loose in environment as regard to browser security.

Offline First Design

You can easily design your application to function in an offline mode without entirely depending on an Internet connection for every action except you need to connect to external resources or update a particular set of data. You will also need to consider design patterns to implement this effectively.

Who Is Using Electron?

A lot of apps such as the new Skype https://electronjs.org/apps/skype.

Slack for messaging, Etcher for burning image files, Github Desktop for versioning and many other apps are built on Electron. You can check out the list of other apps here: https://electronjs.org/apps

How Does Electron Work?

Electron apps run in two processes, the main process and the render process. Each of these two processes has a specific responsibility within your application and while Electron provides a good collection of Node modules for use within your application, many of these modules are only available within a specific process.

The Main Process

This is where your application will handle various system-level activities like creating and managing BrowserWindow instances and various application events. Like the life-cycle events (starting up, preparing to quit, actually quitting, switching between the foreground and background, creating application menus and native dialogs. The main process is what is used to bootstrap the application, the entry point will point to a JS file which will be referenced within our package.json file.

The Render Process

The render process is one which runs the user-interface of your app, each of these render processes will load your content and execute it within its own thread. We can spawn as many windows as we need for our application. The render process is isolated from any interaction with any system-level events. Those interactions must be done within the main process.

How do I communicate between processes?

Electron uses an interprocess communication system to allow for events and data to be passed back and forth — same as Chromium. But in this case between the main and any renderer process.

Also, your Electron app actually does not need to have a render process, but it most likely will. It is a good option for taking your Node scripts and making them easier to use.

Our first “Hello World” example

Now that we have information about Electron’s advantages and processes, we can easily move forward to making our first Electron “Hello World” sample by Installing Electron. We need to follow these steps:

Getting your work environment configured & ready to use Electron is fairly straightforward, there are a couple of items required to get you started.

I will share some links that can get you started on Installation of the requirements needed for this Hello World example, I will be focusing solely on Electron installation and usage in this Article.

Step 1: Install Node

Install Node for MacOs: https://bit.ly/2Atecv4

Install Node for Windows: https://bit.ly/2QVOOqC

Step 2: Install GIT

Install Git on MacOS: https://bit.ly/2Cf62ao

Install Git on Windows: https://bit.ly/2Cey7P2

Step 3: Install Electron

I will guide you on this step as this article is mainly focused on that, for this example, I would be installing Electron on my Desktop on MacOs.

Create a folder named “helloworld_example” and Navigate to it

cd Desktop/helloworld_example
npm init

Once you enter that command, it will prompt you to enter your package.json details such as package name, version, entry point, author etc.

The enter npm install command

npm install electron

Optionally

You can also install the electron command globally in your $PATH:

npm install –g electron

When running npm install electron, some users occasionally encounter installation errors, you can run electron with -allowroot permission.

sudo npm install -g electron — unsafe-perm=true — allow-root

First, npm is the utility we are using to install Electron. Secondly, install is the command. Third, the –g is shorthand for global, meaning our intention is to install Electron globally, making it accessible from anywhere on our computer.

— unsafe-perm=true is to ignore unsafe permission errors, in this case permission is granted by you (as the user) to install electron & ignore permission errors, so no worries as this comes from you (the user).

— allow-root is to allow root access or permission as you are using sudo.

Finally, electron, obviously is the name of the package we are installing. Note that the name is lowercase.

Now you should navigate to your folder on Desktop to check to verify if Electron installs properly

Desktop/helloworld_example/node_modules/electron

Now that we have our electron set up, lets create our index.js and index.html files

Firstly, open your package.json file in your helloworld_example directory and modify to allow electron start your index.js file.

Change this line:

"test": "echo \"Error: no test specified\" && exit 1"

To:

“start”: “electron index.js”

This is how the file should look like below:

{
"name": "helloworld_example",
"version": "1.0.0",
"description": "An hello world sample for Electron ",
"main": "main.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "authorname <author@xyz.com>",
"license": "ISC",
"dependencies": {
"electron": "^3.0.12"
}
}

Secondly, lets create our index.js and index.html file in the same “helloworld_example”directory.

index.js

const electron = require('electron')
const {app, BrowserWindow} = electron
app.on('ready', () => {
let win = new BrowserWindow({width:800, height:600})
win.loadURL(`file://${__dirname}/index.html`)
})

index.html

<!doc html>
<html>
<head>
<title>Hello World Example</title>
</head>
<body>
<h1>Hello World!!!</h1>
</body>
</html>

Then enter npm start command and you should see your app with your text “Hello World!!!” and we’re done.

npm start

Getting started using the quick start code :-)

If you’d love to go ahead and start some real development with Electron, the quick start code is a great place to start, this is where I would explain in detail.

The first step is to clone the electron-quick-start repo, I assume we’re still using Desktop as our example directory.

cd Desktop
git clone https://github.com/electron/electron-quick-start quick-start

This command clones the Electron Quick Start repo inside your local quick-start folder, change directories into quick-start directory & clear the repo history.

cd quick-start
git init

You should get a response like this below:

Reinitialized existing Git repository in /Users/<username>/Desktop/quick-start/.git/

Then you run npm install command, if you’re having permission issues you can run with -allowroot permission, I explained -unsafe-perm & -allow-root options earlier.

sudo npm install -unsafe-perm=true -allow-root

Firstly, you should update your package.json file to set up your quick-start electron project. The file looks like this below:

{
"name": "electron-quick-start",
"version": "1.0.0",
"description": "A minimal Electron application",
"main": "main.js",
"scripts": {
"start": "electron ."
},
"repository": "https://github.com/electron/electron-quick-start",
"keywords": [
"Electron",
"quick",
"start",
"tutorial",
"demo"
],
"author": "GitHub",
"license": "CC0-1.0",
"devDependencies": {
"electron": "^3.0.7"
}
}

I will explain some few important things to take note of:

  • Main” option is very important, this is where you specify the code for the Main Process. If you decide to create a directory for this file to keep your project’s structure neat, you will need to update this node to reflect that change. Otherwise, Electron will not run.
  • scripts”: This key tells Node Package Manager (npm) what actions to take for specific commands. Here, entering npm run start results in the command electron.
  • repository”: This key points to the repository where your code is stored. Feel free to change this to your repository.
  • license”: This is the license code you should specify to provide legally binding guidelines for the use and distribution of your app, you can find over 500 license types at this link: https://gist.github. com/robertkowalski/7620849. Before releasing your app, you should take the time to examine your licensing options.
  • Dependencies” and “devDependencies”: These are a list of names and versions of modules that are required for the project. There is currently no dependencies key for this project.

If you run the npm start command, you should see something like this below:

npm start

Open the main process file

The main process file is named main.js and located under your quick-start directory, While you may decide to organise the code for your Main process into a custom directory and file structure, you should keep a main.js file to represent the starting point for your project.

Your main.js file should look just like this:

The app constant gives access to the event life cycle of your app while the BrowserWindow constant represents your Renderer Process, BrowserWindow is used to create an instance of Chromium which is the window that encloses the User Interface of your app.

The part and url constants represents Node modules, url is used to help in creating URLs while Path helps in dealing with files and directories.

In the createWindow() method above, it perform the following operation:

  • An Instance of BrowserWindow is created and passed along an object to configure window size (width & height)
  • Window is loaded using provided path & url modules to access index.html file.
  • mainWindow.webContents.openDevTools() opens up the Developer tools that are included in Chromium which is helpful is debugging.
  • Listens for ‘closed’ events so as to manage multiple windows if app uses them.

Looking at the bottom of the main.js file, we are allowed to add more Main Process code here or require other files.

Now lets take a look at the index.html file & find out what magic happens there

If you open your file, It should look something like this below:

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Hello World!</title>
</head>
<body>
<h1>Hello World!</h1>
<! - All of the Node.js APIs are available in this renderer process. →
We are using Node.js <script>document.write(process.versions.node)</script>,
Chromium <script>document.write(process.versions.chrome)</script>,
and Electron <script>document.write(process.versions.electron)</script>.
</body>
<script>
// You can also require other files to run in this process
require('./renderer.js')
</script>
</html>

Looking closely, in the middle of the page there are several script tags that contain calls to Node’s process API, all of Node’s APIs are available to the renderer process, that is why you need access to the process API inside this HTML file. In this instance, the code lets us see which versions of Node, Chromium, and Electron are being used with this app.

Conclusion

Going further with Electron.

Now I think you should go further from this quick-start and build a robust electron app, I have skipped some explanations and this is due to making this introduction as short as possible.

If your dream future involves building a cross-platform app, Electron is the way & is intuitive and a great place to start for desktop apps.

Pick an idea that’s going to motivate you, init a repository and just do it.

References

Electron from Beginner to Pro-1 by Griffith, Chris, Wells, Leif

Electron documentation

--

--

Tosin Onikute

Mobile Developer, Native Android & iOS. I play around with RN, Electron.