• Whizzystack Solutions

Creating Your First Desktop App With Electron



Creating Your First Desktop App with HTML, JS and Electron


Web applications become a lot of and a lot of powerful per annum, however there's still area for desktop apps with full access to the hardware of your pc. Nowadays you'll be able to produce desktop apps victimization the already acquainted hypertext mark-up language, JS and Node.js, then package it into associate degree practicable file and distribute it consequently across Windows, OS X and UNIX system. There square measure 2 widespread open supply comes that build this doable. These square measure nor'-west.js, that we have a tendency to lined a number of months past, and therefore the newer lepton, that we have a tendency to square measure reaching to use nowadays (see the variations between them here). we have a tendency to square measure reaching to rewrite the older nor'-west.js version to use lepton, therefore you'll be able to simply compare them.


Getting Started With Electron


Apps engineered with Electron are simply websites that unit opened in associate embedded metal applications programme. Additionally to the regular HTML5 genus APIs, these websites will use the complete suite of Node.js modules and special lepton modules that offer access to the software package. For the sake of this tutorial, we are going to be building an easy app that fetches the foremost recent Tutorialzine articles via our RSS feed and displays them in a very cool trying carousel.


All the files required for the app to figure area unit obtainable in associate archive that you'll be able to get from the transfer button close to the highest of the page. Extract its contents in a very directory of your alternative. Judgment by the file structure, you'd never guess this is often a desktop application and not simply an easy web site.









We will take a closer look at the more interesting files and how it all works in a minute, but first, let's take the app for a spin.


Running the App


Since an Electron app is just a fancy Node.js app, you will need to have npm installed. You can learn how to do it here, it's pretty straightforward.


Once you've got that covered, open a new cmd or terminal in the directory with the extracted files and run this command:

 npm install
 

This will create a node_modules folder containing all the Node.js dependencies required for the app to work. Everything should be good to go now, in the same terminal as before enter the following:

npm start

The app should open up in it's own window. Notice it has a top menu bar and everything!


You've most likely detected that beginning the app is not too user friendly. However, this is often simply the developer's method of running associate degree negatron app. once prepacked for the general public, the it'll be put in sort of a traditional program and opened like one, simply by double clicking on its icon.


How It's Created


Here, we'll bring up the foremost essential files in any negatron app. Let's begin with package.json, that holds numerous data regarding the project, like the version, npm dependencies and alternative vital settings


package.json

{
 "name": "electron-app",
 "version": "1.0.0",
 "description": "",
 "main": "main.js",
 "dependencies": {
 "pretty-bytes": "^2.0.1"
 },
 "devDependencies": {
 "electron-prebuilt": "^0.35.2"
 },
 "scripts": {
 "start": "electron main.js"
 },
 "author": "",
 "license": "ISC"
}

If you've got worked with node.js before, you already acumen this works. The foremost important issue to notice here is that the scripts property, wherever we've outlined the npm start command, permitting US to run the app like we have a tendency to do earlier. After we decision it, we have a tendency to raise lepton to run the most.js file. This JS file contains a brief script that opens the app window, and defines some choices and event handlers.


main.js

var app = require('app'); // Module to control application life.
var BrowserWindow = require('browser-window'); // Module to create native browser window.
 
// 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.
var mainWindow = null;
 
// 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();
 }
});
 
// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
app.on('ready', function() {
 // Create the browser window.
 mainWindow = new BrowserWindow({width: 900, height: 600});
 
 // and load the index.html of the app.
 mainWindow.loadURL('file://' + __dirname + '/index.html');
 
 // 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;
 });
});

Take a glance at what we have a tendency to liquidate the 'ready' technique. Initial we have a tendency to outline a browser window and set it's initial size. Then, we have a tendency to load the index.html get into it that works equally to gap a HTML get into your browser.


As you'll see, the HTML file itself is nothing special - a instrumentation for the carousel and a paragraph were central processing unit and RAM stats area unit displayed.


index.html

<!DOCTYPE html>
<html>
<head>
 
 <meta charset="utf-8">
 <meta name="viewport" content="width=device-width, initial-scale=1">
 
 <title>Tutorialzine Electron Experiment</title>
 
 <link rel="stylesheet" href="./css/jquery.flipster.min.css">
 <link rel="stylesheet" href="./css/styles.css">
 
</head>
<body>
 
<div class="flipster">
 <ul>
 </ul>
</div>
 
<p class="stats"></p>
 
<!-->In Electron, this is the correct way to include jQuery<-->
<script>window.$ = window.jQuery = require('./js/jquery.min.js');</script>
<script src="./js/jquery.flipster.min.js"></script>
<script src="./js/script.js"></script>
</body>
</html>

The hypertext mark-up language conjointly links to the required stylesheets, JS libraries and scripts. Notice that jQuery is enclosed in a very weird approach. See this issue for additional info that. Finally, here is that the actual JavaScript for the app. In it we have a tendency to access Tutorialzine's RSS feed, fetch recent articles and show them. If we have a tendency to try and do that in a very browser atmosphere, it will not work, as a result of the RSS feed is found on a unique domain and taking from it's proscribed. In negatron, however, this limitation does not apply and that we will merely get the required info with associate AJAX request.

$(function(){
 
 // Display some statistics about this computer, using node's os module.
 
 var os = require('os');
 var prettyBytes = require('pretty-bytes');
 
 $('.stats').append('Number of cpu cores: <span>' + os.cpus().length + '</span>');
 $('.stats').append('Free memory: <span>' + prettyBytes(os.freemem())+ '</span>');
 
 // Electron's UI library. We will need it for later.
 
 var shell = require('shell');
 
 // Fetch the recent posts on Tutorialzine.
 
 var ul = $('.flipster ul');
 
 // The same-origin security policy doesn't apply to electron, so we can
 // send ajax request to other sites. Let's fetch Tutorialzine's rss feed:
 
 $.get('http://feeds.feedburner.com/Tutorialzine', function(response){
 
 var rss = $(response);
 
 // Find all articles in the RSS feed:
 
 rss.find('item').each(function(){
 var item = $(this);
 
 var content = item.find('encoded').html().split('</a></div>')[0]+'</a></div>';
 var urlRegex = /(http|ftp|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&amp;:/~\+#]*[\w\-\@?^=%&amp;/~\+#])?/g;
 
 // Fetch the first image of the article.
 var imageSource = content.match(urlRegex)[1];
 
 // Create a li item for every article, and append it to the unordered list.
 
 var li = $('<li><img /><a target="_blank"></a></li>');
 
 li.find('a')
 .attr('href', item.find('link').text())
 .text(item.find("title").text());
 
 li.find('img').attr('src', imageSource);
 
 li.appendTo(ul);
 
 });
 
 // Initialize the flipster plugin.
 
 $('.flipster').flipster({
 style: 'carousel'
 });
 
 // When an article is clicked, open the page in the system default browser.
 // Otherwise it would open it in the electron window which is not what we want.
 
 $('.flipster').on('click', 'a', function (e) {
 
 e.preventDefault();
 
 // Open URL with default browser.
 
 shell.openExternal(e.target.href);
 
 });
 
 });
 
});

A cool thing about the above code, is that in one file we simultaneously use:


· JavaScript libraries - jQuery and jQuery Flipster to make the carousel.

· Electron native modules - Shell which provides APIs for desktop related tasks, in our case opening a URL in the default web browser.

· Node.js modules - OS for accessing system memory information, Pretty Bytes for formatting.


And with this our app is ready!


Packaging and Distribution


There is one necessary issue to try to form your app prepared for finish users. You would like to package it into associate degree possible which will be started with a double click on users' machines. Since negatron apps will work on multiple operational systems and each OS is completely different, there have to be compelled to be separate distributions for Windows, for OS X and for UNIX system. Tools like this npm module square measure a decent place to begin - Electron Packager.


Take into thought that the packaging takes all of your assets, all the specified node.js modules, and a minified WebKit browser and places them along in an exceedingly single possible file. Of these things add up and therefore the outcome is associate degree app that's roughly 50mb in size. This can be quite a ton and is not sensible for an easy app like our example here; however this becomes impertinent once we work with huge, advanced applications.


Conclusion


The only major distinction with NW.js that you simply can see in our example is that NW.js opens Associate in Nursing hypertext mark-up language page directly, whereas lepton starts up by corporal punishment a JavaScript file Associate in producing an application window through code. Electron's manner provides you additional management, as you'll be able to simply build multi-window applications and organize the communication between them.

Overall Electron is Associate in building exciting desktop internet applications victimization internet technologies. Here is what you ought to scan next:

· Electron's Quick Start Guide

· Electron's Documentation

· Apps Built with Electron


We will be happy to answer your questions on designing, developing, and deploying comprehensive enterprise web, mobile apps and customized software solutions that best fit your organization needs.

As a reputed Software Solutions Developer we have expertise in providing dedicated

remote and outsourced technical resources for software services at very nominal cost. Besides experts in full stacks We also build web solutions, mobile apps and work on system integration, performance enhancement, cloud migrations and big data analytics. Don’t hesitate to get in touch with us!

40 views

Recent Posts

See All
 You can unsubscribe in one click, and I will never share your email address.

About Whizzystack

  • LinkedIn
  • Facebook
  • Twitter
  • Instagram
  • RSS

We are User Experience Consultant, Conversion Rate Optimization Specialist and expert in digital transformation. We help savvy marketers, product owners and UX advocates make the case that a useable, accessible and people-first experience is the best path to business success. All the while pursuing his not-so-hidden agenda. We also build & support your own talented, trusted, full-time development team hosted out of Whizzystack’s headquarters in India. We also deliver world class product and software development services Read more

What We Do

Software Development

Web Application Development

Mobile Application Development Web Portal Development

Ecommerce Development

Custom Software Development

Web Presence

UI/UX Development

Digital Marketing

Social Media Management

Search Engine Optimization

Online Reputation Management

Web Experience

UI/UX Prototyping

System Designing

Service Designing 

System Integration

Performance Optimization

Our Developers

Contact Whizzystack

USA :     +1(877)3685420

India:    +91(95)60641297

              +91(120)4287309

111, Pemberton Brown Mills Road,

Brown Mills, New Jersey, USA, 08015

Bouleward Walk, Habitapur, Noida, Uttar Pradesh, India, 20109