Building desktop applications with Electron - BrowserWindow

Janez Čadež
2 min readMay 21, 2017

--

The BrowserWindow module gives you the ability to create new application windows in your app. We will begin by creating new BrowserWindow with the click of a button.

Start by adding button with id of new-window to the index.html file at the end of body tag. The text of button should be “Create new window”. We are providing id because we will use it to reference element in JavaScript file.

<button id=”new-window”>Create new window</button>

Now, navigate to the renderer.js file, we will put our logic code here. Start by creating creating new const BrowserWindow and loading the electron package and assigning remote.BrowserWindow to the constant. Also, let’s create path constant and load ‘path’ module.

const BrowserWindow = require(‘electron’).remote.BrowserWindowconst path = require(‘path’)

Great, now let’s use our id from the button and define const newWindowBtn. We can get a reference to element by using document.getElementById and specifying our button id.

const newWindowBtn = document.getElementById(‘new-window’)

And the last thing we need to do is to define new click event listener. Do this by calling newWindowBtn.addEventListener and passing ‘click’ as a parameter and anonymous function with an event parameter. Inside the function we will define new variable win and assign BrowserWindow to it. Browser window will be 500px wide and 500px high.

newWindowBtn.addEventListener(‘click’, function (event) {   let win = new BrowserWindow({ width: 500, height: 500 })})

We want to load GitHub website in this new window, so we will call win.loadURL and specify the URL of ‘https://github.com’ in the string. We configured this new window and can display it by calling win.show().

win.loadURL(‘https://github.com')win.show()

The last thing for us is to define our window closing functionality. When we close the app with the click on X, the ‘close’ event will be emitted. We will catch it and dereference the win variable. Add win.on(‘close’), define a anonymous function and assign null to our win variable.

win.on(‘close’, function () { win = null })

--

--

Janez Čadež

JavaScript Engineer @poviolabs, Udemy instructor, open source contributor. https://devhealth.io