Today in Impostor Syndrome #11 — How to wire up a button to close the main Electron app

To learn Electron, I’ve been separating each of the electron-api-demo demos into individual apps. I find having smaller, bite-sized chunks helps me ramp up on a new technology after I’ve mastered Hello World.

This walkthrough will show you how to close this main window.

close this window button closes main window
  1. Starting from scratch, create a new directory.
  2. Create a new package.json file containing the following:

3. From Terminal, run

npm install

This will tell npm to install Electron.

Aside: something that drives me is that I have to keep installing these npm packages. I guess this is a carry-over effect from my Visual Studio days. I keep thinking “I’ve installed it once. it’s already on my local machine. Why do I have to keep reinstalling it??” But now I tell myself, okay this is the equivalent of adding a package in Visual Studio. The circle of life rolls on…

4. Add the index.html file to the directory, containing

I copied the style from the electron-api-demo app because I’m new at this.

5. Add an index.js file to the directory, containing

Now things are getting interesting.

  • Ironically, the most important line is at the bottom, because engineers. As I mentioned in a previous post, you need to wait until the DOM is fully loaded to find the buttons. The document.addEventListener(‘DOMContentLoaded’) takes care of this for us. So we wire up the buttons once the DOM content has been loaded.
  • We need the ipcRenderer to talk to the main window.
  • Within the wireUpButtons() we find the button in the DOM and wire up to it an event listener for the click. Whenever the button is clicked (or in this case a link that can only be clicked once), the ipcRenderer sends a message to the main.js file. Speaking of which…

6. Add a main.js file

Since this is the main.js file, it uses ipcMain. When ipcMain receives the ‘close-app’ message, it does exactly that.

app.quit() quits the app in the terminal

And you’re returned to your already scheduled operating system, already in progress… (inside joke from those who grew up when Mtv actually played videos).