Quickly start a new Electron software project

By: (plus.google.com) +David Herron; Date: June 20, 2018

Tags: Node.JS » Electron

If Electron encapsulates the Chromium web browser to support running GUI applications, isn't it a complex platform to use? Isn't it complex to get started with Electron? Yes, there is a fair amount of complexity under the hood of Electron. Electron really is the guts of the Google Chrome web browser, encapsulated in a Node.js runtime, letting Node.js programmers easily develop desktop GUI applications using web technology. That was a mouthfull to describe, and getting a fully polished application up and running has some complexity. Thanks to starter projects maintained by the Electron team, getting a skeleton application running is quick.

What we'll do is walk through one of the starter applications and discuss what's there.

This article is part of a series on kicking the tires of Electron application development. See:

Namely: (github.com) https://github.com/electron/electron-quick-start

QUICK START:

$ git clone https://github.com/electron/electron-quick-start
Cloning into 'electron-quick-start'...
remote: Counting objects: 289, done.
remote: Total 289 (delta 0), reused 0 (delta 0), pack-reused 289
Receiving objects: 100% (289/289), 59.89 KiB | 901.00 KiB/s, done.
Resolving deltas: 100% (133/133), done.
$ cd electron-quick-start
$ npm install

> electron@2.0.2 postinstall /Volumes/Extra/sourcerer/004-electron/electron-quick-start/node_modules/electron
> node install.js

Downloading SHASUMS256.txt
[============================================>] 100.0% of 5.33 kB (5.33 kB/s)
electron@2.0.2 node_modules/electron
├── @types/node@8.10.20
├── extract-zip@1.6.7 (debug@2.6.9, yauzl@2.4.1, mkdirp@0.5.1, concat-stream@1.6.2)
└── electron-download@3.3.0 (semver@5.5.0, home-path@1.0.6, minimist@1.2.0, path-exists@2.1.0, rc@1.2.8, debug@2.6.9, sumchecker@1.3.1, fs-extra@0.30.0, nugget@2.0.1)

$ npm start

> electron-quick-start@1.0.0 start /Users/David/electron-quick-start
> electron .

Ah, there's a pre-requisite that's obvious - first, install Node.js. But if you're here you probably already have Node.js installed. If not, consult:

The skeleton electron app in its full glory

Okay, we're done right? That's all there is? Before we leave, let's take a quick look at the source

The files associated with the skeleton application

It's a small list of files, so it'll be quick to go over this. The file hierarchy isn't what gets used in larger Electron applications, but it works in this case.

package.json

{
  "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": "^2.0.0"
  }
}

Let's start with the package.json. It declares main as main.js, which we'll look at shortly.

The start script runs electron .. The electron command was installed by the electron package -- see the devDependencies section -- and provides the method to launch an Electron application. Running the command without options gives this help text:

$ electron

  Electron 2.0.2 - Build cross platform desktop apps with JavaScript, HTML, and CSS
  Usage: electron [options] [path]

  A path to an Electron app may be specified. It must be one of the following:
    - index.js file.
    - Folder containing a package.json file.
    - Folder containing an index.js file.
    - .html/.htm file.
    - http://, https://, or file:// URL.

  Options:
    -d, --default         Run the default bundled Electron app.
    -i, --interactive     Open a REPL to the main process.
    -r, --require         Module to preload (option can be repeated).
    -v, --version         Print the version.
    -a, --abi             Print the Node ABI version.

So, electron . uses the scenario Folder containing a package.json file.

main.js

As the name implies, this module initializes the application.

const {app, BrowserWindow} = require('electron')

The Electron team likes to destructure objects like this - and this idiom is meant to be similar to ES6 modules.

The app object is a handle for the application. BrowserWindow is a class that encapsulates, as the name implies, a top-level Browser window.

Recall that Electron encapsulates the guts of Chrome. That means a Window in an Electron application is really a Browser window.

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.on('ready', createWindow)

The app object provides an on EventEmitter listener mechanism you use as so. The ready event is emitted when the application is, well, ready. The skeleton application will also call createWindow via an activate event.

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

  // and load the index.html of the app.
  mainWindow.loadFile('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
  })
}

We initialize a new BrowserWindow, assigning it to a global-to-this-module variable. In the next line we load an index.html into that browser -- the actual user interface is written in HTML. Interactivity is implemented by browser-style JavaScript running inside the BrowserWindow.

The closed event is emitted when the user elects to close the application. In this case it sets mainWindow to null, and then if all windows are closed we get this event:

// 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()
  }
})

When all windows are closed, we call app.quit() to close the application process. For Mac OS X this is written to require the user to type CMD+Q instead.

That's the basic of launching the application, making something appear, and quitting the application.

index.html

The user interface is implemented with HTML code. Such as:

<!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>.

    <script>
      // You can also require other files to run in this process
      require('./renderer.js')
    </script>
  </body>
</html>

For the most part this is HTML you'd write on a regular website. It's nice clean modern HTML5 code. Compare the code here, especially the first few <script> tags, with the screen capture earlier.

But... that last <script> tag uses a require statement. What's up with that?

Electron brings a few Node.js features into what looks like browser-side JavaScript. Such as the ability to use require to load modules.

In this case it loads in ./renderer.js which is:

// This file is required by the index.html file and will
// be executed in the renderer process for that window.
// All of the Node.js APIs are available in this process.

What's that about a renderer process?

Electron's process structure

Electron has a Main process and one or more Renderer processes. The Main process is the one which runs the script listed in the main tag of package.json. There can be only one Main process.

Each web page in Electron runs in its own Renderer process. This is because of Chromium's multi-process architecture, where each open browser tab in Chrome has its own process. Electron Renderer processes follow the same model.

Electron provides an inter-process-communication system so the two can communicate. Events are sent between the Main process and the Renderer processes. A Renderer process can request the Main process take some actions, etc.

From the documentation ( (electronjs.org) https://electronjs.org/docs/tutorial/application-architecture):

In web pages, calling native GUI related APIs is not allowed because managing native GUI resources in web pages is very dangerous and it is easy to leak resources. If you want to perform GUI operations in a web page, the renderer process of the web page must communicate with the main process to request that the main process perform those operations.

Conclusion

That's a good basis for beginning to understand Electron application development.

« Learn the MERN stack with this video tutorial series How to run JavaScript in the command-line environment »
2016 Election 2018 Elections Acer C720 Ad block Air Filters Air Quality Air Quality Monitoring AkashaCMS Amazon Amazon Kindle Amazon Web Services America Amiga and Jon Pertwee Android Anti-Fascism AntiVirus Software Apple Apple Hardware History Apple iPhone Apple iPhone Hardware April 1st Arduino ARM Compilation Artificial Intelligence Astronomy Astrophotography Asynchronous Programming Authoritarianism Automated Social Posting AWS DynamoDB AWS Lambda Ayo.JS Bells Law Big Brother Big Data Big Finish Big Science Bitcoin Mining Black Holes Blade Runner Blockchain Blogger Blogging Books Botnets Cassette Tapes Cellphones China China Manufacturing Christopher Eccleston Chrome Chrome Apps Chromebook Chromebox ChromeOS CIA CitiCards Citizen Journalism Civil Liberties Climate Change Clinton Cluster Computing Command Line Tools Comment Systems Computer Accessories Computer Hardware Computer Repair Computers Conservatives Cross Compilation Crouton Cryptocurrency Curiosity Rover Currencies Cyber Security Cybermen Cybersecurity Daleks Darth Vader Data backup Data Formats Data Storage Database Database Backup Databases David Tenant DDoS Botnet Department of Defense Department of Justice Detect Adblocker Developers Editors Digital Nomad Digital Photography Diskless Booting Disqus DIY DIY Repair DNP3 Do it yourself Docker Docker MAMP Docker Swarm Doctor Who Doctor Who Paradox Doctor Who Review Drobo Drupal Drupal Themes DVD E-Books E-Readers Early Computers eGPU Election Hacks Electric Bicycles Electric Vehicles Electron Eliminating Jobs for Human Emdebian Encabulators Energy Efficiency Enterprise Node EPUB ESP8266 Ethical Curation Eurovision Event Driven Asynchronous Express Face Recognition Facebook Fake News Fedora VirtualBox Fifth Doctor File transfer without iTunes FireFly Flash Flickr Fraud Freedom of Speech Front-end Development G Suite Gallifrey git Github GitKraken Gitlab GMAIL Google Google Chrome Google Gnome Google+ Government Spying Great Britain Green Transportation Hate Speech Heat Loss Hibernate High Technology Hoax Science Home Automation HTTP Security HTTPS Human ID I2C Protocol Image Analysis Image Conversion Image Processing ImageMagick In-memory Computing InfluxDB Infrared Thermometers Insulation Internet Internet Advertising Internet Law Internet of Things Internet Policy Internet Privacy iOS Devices iPad iPhone iPhone hacking Iron Man iShowU Audio Capture iTunes Janet Fielding Java JavaFX JavaScript JavaScript Injection JDBC John Simms Journalism Joyent Kaspersky Labs Kext Kindle Kindle Marketplace Large Hadron Collider Lets Encrypt LibreOffice Linux Linux Hints Linux Single Board Computers Logging Mac Mini Mac OS Mac OS X Machine Learning Machine Readable ID Macintosh macOS macOS High Sierra macOS Kext MacOS X setup Make Money Online March For Our Lives MariaDB Mars Mass Violence Matt Lucas MEADS Anti-Missile Mercurial MERN Stack Michele Gomez Micro Apartments Microsoft Military AI Military Hardware Minification Minimized CSS Minimized HTML Minimized JavaScript Missy Mobile Applications Mobile Computers MODBUS Mondas Monetary System MongoDB Mongoose Monty Python MQTT Music Player Music Streaming MySQL NanoPi Nardole NASA Net Neutrality Network Attached Storage Node Web Development Node.js Node.js Database Node.js Performance Node.js Testing Node.JS Web Development Node.x North Korea npm NVIDIA NY Times Online advertising Online Community Online Fraud Online Journalism Online Photography Online Video Open Media Vault Open Source Open Source and Patents Open Source Governance Open Source Licenses Open Source Software OpenAPI OpenJDK OpenVPN Palmtop PDA Patrick Troughton PayPal Paywalls Personal Flight Peter Capaldi Peter Davison Phishing Photography PHP Plex Plex Media Server Political Protest Politics Postal Service Power Control President Trump Privacy Production use Public Violence Raspberry Pi Raspberry Pi 3 Raspberry Pi Zero ReactJS Recaptcha Recycling Refurbished Computers Remote Desktop Removable Storage Republicans Retro Computing Retro-Technology Reviews RFID Rich Internet Applications Right to Repair River Song Robotics Robots Rocket Ships RSS News Readers rsync Russia Russia Troll Factory Russian Hacking Rust SCADA Scheme Science Fiction SD Cards Search Engine Ranking Season 1 Season 10 Season 11 Security Security Cameras Server-side JavaScript Serverless Framework Servers Shell Scripts Silence Simsimi Skype SmugMug Social Media Social Media Networks Social Media Warfare Social Network Management Social Networks Software Development Software Patents Space Flight Space Ship Reuse Space Ships SpaceX Spear Phishing Spring Spring Boot Spy Satellites SQLite3 SSD Drives SSD upgrade SSH SSH Key SSL Stand For Truth Strange Parts Swagger Synchronizing Files Tegan Jovanka Telescopes Terrorism The Cybermen The Daleks The Master Time-Series Database Tom Baker Torchwood Total Information Awareness Trump Trump Administration Trump Campaign Twitter Ubuntu Udemy UDOO US Department of Defense Virtual Private Networks VirtualBox VLC VNC VOIP Vue.js Walmart Weapons Systems Web Applications Web Developer Resources Web Development Web Development Tools Web Marketing Webpack Website Advertising Weeping Angels WhatsApp William Hartnell Window Insulation Windows Windows Alternatives Wordpress World Wide Web Yahoo YouTube YouTube Monetization