Home > Enterprise >  How do I make button close Electron-JS app?
How do I make button close Electron-JS app?

Time:12-08

Code:

index.html

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self'">
    <link rel="stylesheet" type="text/css" href="index.css">
    <title>Youtify</title>
  </head>
  <body>
        <div id = "leftBar"></div>
        <div id = "rightBar"></div>
        <div id = "bottomBar"><hr></div>
        <div id = "toolButtons">
          <div id ="closeBtn"><a data-text="✖"></a></div>
          <div id="maxBtn"><a data-text="❐" ></a></div>
          <div id="minBtn"><a data-text="─" ></a></div>
        </div>
    <script src="./renderer.js"></script>
  </body>
</html>

main.js

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

function createWindow () {   const mainWindow = new BrowserWindow({
    width: 800,
    height: 600,
    frame: false,   })

  mainWindow.loadFile('index.html') }

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

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

renderer.js

// close app
function closeApp(e) {
  e.preventDefault();
  app.quit();
}

document.getElementById("closeBtn").addEventListener("click", closeApp);

What I want is to click on the button with the id "closeBtn" to close the app, I was looking for it, but I just can't make it working. Can anyone please help?

CodePudding user response:

Try using ipcRenderer to send the close command to main.js

In your main.js:

ipcMain.on('close', () => {
  app.quit()
})

Then, in your renderer.js:

const ipc = require('electron').ipcRenderer

// close app
function closeApp(e) {
  e.preventDefault()
  ipc.send('close')
}

document.getElementById("closeBtn").addEventListener("click", closeApp);
  • Related