Trying Your Web App in Electron

Nic Ridder

Electron is a framework for creating native applications with web technologies like JavaScript, HTML, and CSS. It takes care of the hard parts so you can focus on the core of your application. Electron provides switches to determine if you are running on the web or as a desktop client that enables you to activate rich features like file system access. If your app isn’t very reliant on actually being connected to the internet, you can even have your app run offline through Electron.

If you already have an existing app you may want to try out your app in Electron without rearranging your code.  Fortunately, it’s a snap!

Before we get started I recommend you have Node and NPM installed.

Let’s start by cloning the electron-quick-start.  Open your command line interface and change directory to the ‘electron-quick-start’ directory we just cloned.  Now let’s install our dependencies by entering ‘npm install’ into our console.  Once that is finished, enter ‘npm start’ into the console and you should be treated to a ‘Hello World!’ display running in Electron.

We’re up and running, but now let’s point this to our own application.  First make sure your code is running, whether online or locally hosted.

Close out of the Hello World! Electron app. Open the electron-quick-start folder in your file explorer and open the main.js file in a text editor.  In that file find the function called createWindow and within that you should find a line that looks something like:

mainWindow.loadURL(url.format({

    pathname: path.join(__dirname, ‘index.html’),

    protocol: ‘file:’,

    slashes: true

  }))

That piece of code points the Electron browser (known as Chromium) at the index.html file in the same folder.  Instead let’s comment that code out and put our own code in it’s place:

mainWindow.loadURL(“http://mywebapp.com”);

Obviously, you’ll want to replace ‘mywebapp.com’ with wherever your code happens to be hosted (if you’re hosting locally, make sure to keep the http or https prefix) and then save the file.

Now let’s run this.  Quick warning before we go any further: Do not point loadURL to a website that isn’t yours or one that you don’t trust. Untrusted websites could exploit Electron to harm your computer.

Go back to your command line interface and enter ‘npm start’. The newly created window should be running your application. Pretty cool, right?

Of course, this is all just the tip of the iceberg with Electron. For more information, I recommend checking out the documentation over at https://electron.atom.io.

Leave a comment