6

I have looked at the documentation for Electron regarding the 'frameless-window', but I just can't seem to make a button of my own work to close the application...

Any help would be appreciated! Thanks!

const electron = require('electron');
const url = require('url');
const path = require('path');

const {app, BrowserWindow} = electron;
let mainWindow;

// Listen for app to be ready
app.on('ready', function() {
  // create new window
  mainWindow = new BrowserWindow({width: 800, height: 600, frame: false});
  // Load html into window
  mainWindow.loadURL(url.format({
    pathname:path.join(__dirname,'main.html'),
    protocol: 'file:',
    slashes: true
  }));
  const closeApp = document.getElementById('closeApp');

  closeApp.addEventListener('click', () => {
    app.quit();
  });
});
<!DOCTYPE html>
<html lang="en">
<head>
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Electron "Hello World"</title>
</head>
<body>
  <header>
    <p id="closeApp">close app</p>
  </header>
</body>
</html>
pergy
  • 5,285
  • 1
  • 22
  • 36
hannacreed
  • 639
  • 3
  • 15
  • 34

2 Answers2

23

In your renderer process (javascript loaded from main.html) you should be able to load Electron and Node modules.

const {ipcRenderer} = require('electron');
const closeApp = document.getElementById('closeApp');
closeApp.addEventListener('click', () => {
    ipcRenderer.send('close-me')
});

In main.js the script you posted

const {ipcMain} = require('electron')
ipcMain.on('close-me', (evt, arg) => {
  app.quit()
})
Leonardo Buscemi
  • 1,111
  • 1
  • 15
  • 22
  • You are a savior! +1 – Roman Kozin Apr 11 '21 at 23:20
  • As of 02/2022, This does not resolve the issue by default. Error in console 'Uncaught ReferenceError: require is not defined'. You have to actually add the 'const { ipcRenderer } = require('electron');' in the 'preload.js' script. – dbrree Feb 08 '22 at 18:07
2

As of 2022, the confirmed solution will produce an error in console 'Uncaught ReferenceError: require is not defined'. We won't be utilizing the 'renderer.js' script in this example.

These are the steps to solve this:

In the Preload.js script

const { ipcRenderer } = require('electron');

document.getElementById('closeApp').addEventListener('click', () => {
  ipcRenderer.invoke('quit-app');
});

In the Main.js script

ipcMain.handle('quit-app', () => {
  app.quit();
});
dbrree
  • 613
  • 7
  • 23