Electron

Build cross platform desktop apps with JavaScript, HTML, and CSS

Electron is a node-based system that makes it very easy to convert your website into a desktop app. Beneath the surface, Electron uses the Chromium rendering engine and the nodejs runtime, to complete the task. Electron is developed and maintained by github.

Electron makes it possible to build cross platform desktop apps using web-technology – and it is the main GUI framework behind several large scale desktop applications, such as Github Desktop and Visual Studio Code.

Basically an electron application is a nodejs application – so to get started, open up your terminal in a suitable folder, and type npm init:

npm init

Go through the steps with minimal attention, and afterwards you will see that a new file has been added to your folder: package.json. This is your project configuration file. It takes little effort to change the default values into an Electron app (instead of a standard node app), so open the file and edit it to match the following contents:

{
  "name": "your_app_name",
  "version": "1.0.0",
  "description": "Well.. testing out Electron",
  "main": "main.js",
  "scripts": {
    "start": "electron ."
  },
  "author": "Mr/Ms You",
  "license": "ISC"
}

The few important lines here, concerns the “main” property, which must be main.js (node typically runs on index.js), and the “start: electron .” command. The latter will allow you to run your application using the electron package instead of node.

At this point we are ready to install electron itself. The recommended way of doing so is to install it as a development dependency in your app, which allows you to experiment with different versions of electron without installing a global version. Go back to your terminal and type:

npm install --save-dev electron

You will see a lot of stuff happening, download bars and messages – maybe even some warnings – but that’s all good for now, we won’t go into details. As long as you end up with a message that don’t contain the word ERROR – you’re all set.

You will also notice that a bunch of new files and folders are added to your project. These are basically the remedies that Electron needs to do it’s work.

Main.js

You probably remember the line main: “main.js” from the package.json file? Well, this is basically telling the app what file to run when your application fires up. So create a new file called main.js in the root of your project folder, and type the following.

const electron = require('electron')

We create a new instance of the ‘electron’ module into a variable we call ‘electron’. From here on we can access electrons capabilities. The module is organised in ‘namespaces’, for example electron.app handles the application lifecycle, while electron.browserWindow can be used to create app windows. Lets extend the code a little bit, so your main.js includes the following code:

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

function createWindow () {
  // Create the browser window.
  let win = new BrowserWindow({
    width: 800,
    height: 400,
    webPreferences: {
      nodeIntegration: true
    }
  })

  // and load the index.html of the app.
  win.loadFile('index.html')
}

app.on('ready', createWindow)

In line 1 we specify which parts of the electron module we will need. On the last line we start the Electron app, by calling one function: createWindow() that is defined from line 3. As you will see shortly, this results in your computer opening an empty, fullscreen chromium window. Head back to the shell and type:

npm start

This points back to your package.json file – remember there was a line called “scripts”, and within that a key called “start” with a value called “electron .”? So, when you type the command “npm start”, the project uses the package.json configuration file to run the electron module. And if all is working out, n empty window opens. Congratulations – you have now completed the first part of making an electron app.

N.B to close your application, go to the terminal and type CTRL+C

Adding webpage content

The next thing we want to do, is to add some content to our app. As promised, electron makes it possible to convert a web-page into a desktop app. So go ahead and add a new file called index.html to your folder – or even better – take any webproject you might have lying around, and include it in the folder. As you might have noticed, the createWindow function in main.js already points to a file called “index.html”. So adding such a file to your project folder will do the trick. Start the project again, and you will find the app presents your webpage content – now as a desktop app.

Wrap up

There is a bit of finishing code you should add to your main.js file. Basically it’s just a bit tidy behaviour in order to handle how you open and close the app window etc. Go ahead and update main.js with the following, and let’s go on to making some more functionality.

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

// 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 win

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

  // and load the index.html of the app.
  win.loadFile('index.html')

  // Open the DevTools.
  win.webContents.openDevTools()

  // Emitted when the window is closed.
  win.on('closed', () => {
    // 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.
    win = null
  })
}

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

// Quit when all windows are closed.
app.on('window-all-closed', () => {
  // On macOS 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', () => {
  // On macOS 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 (win === null) {
    createWindow()
  }
})

// In this file you can include the rest of your app's specific main process
// code. You can also put them in separate files and require them here.

Leave a comment

Din e-mailadresse vil ikke blive publiceret. Krævede felter er markeret med *