21 May, 2021

Electron Notes

mkdir app01
cd app01
npm init -y
npm i --save-dev electron

Add main.js file:

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

function createWindow () {
  const win = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
      preload: path.join(__dirname, 'preload.js')
    }
  })

  win.loadFile('index.html')
}

app.whenReady().then(() => {
  createWindow()

  app.on('activate', () => {
    if (BrowserWindow.getAllWindows().length === 0) {
      createWindow()
    }
  })
})

app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit()
  }
})

Add index.html file:

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Hello World!</title>
    <meta http-equiv="Content-Security-Policy" content="script-src 'self' 'unsafe-inline';" />
</head>
<body style="background: white;">
    <h1>Hello World!</h1>
    <p>
        We are using Node.js <span id="node-version"></span>,
        Chromium <span id="chrome-version"></span>,
        and Electron <span id="electron-version"></span>.
    </p>
</body>
</html>

Add preload.js file:

window.addEventListener('DOMContentLoaded', () => {
  const replaceText = (selector, text) => {
    const element = document.getElementById(selector)
    if (element) element.innerText = text
  }

  for (const type of ['chrome', 'node', 'electron']) {
    replaceText(`${type}-version`, process.versions[type])
  }
})

Update package.json file and replace the author and description with a value.

Start with:

npm start

Add electron-forge CLI:

npm i -D @electron-forge/cli
npx electron-forge import

Build a redistributable package in out folder:

npm run make

todo package the files in a installation executable with maybe Inno Setup?

Adding Feature

Set the App Icon

Update the BrowserWindow parameter and add:

icon: 'icon.png'`,

Where the icon.png is the icon file.

Add an Overlay Icon

Create an icon file notes.png and place it in the root folder.

win.setOverlayIcon('notes.png', 'Changed to notes icon.')

(Are there other image file format supported?)

Show a Notification

Insert a script reference to the index.html file:

    <script src="renderer.js"></script>

Create the renderer.js file:

const myNotification = new Notification('Title', {
  body: 'Notification from the Renderer process'
})

myNotification.onclick = () => {
  console.log('Notification clicked')
}

There is an alternative to show notification from the main process.

Tools

https://github.com/maximegris/angular-electron