You can listen for SIGINT/SIGTERM and stop your app from exiting when the User presses CTRL-C in the terminal (if it was launched from one) in node js using process.on
, but the same did not work in my electron application. I also tried binding handlers to the "quit", "before-quit" and "will-quit" events of the app
object but to no avail. Is it possible to detect if the user opened the app from the terminal and pressed CTRL-C in an electron app, and to bind handlers to it and stop the app from exiting. And if yes, then how would you achieve this?
Here's how I am using process.on
and app.on
in a basic electron Main Process, in case I am doing something wrong (my original script contains alot of code not relevant to the question and what I want to achieve does not work with basic electron-quickstart app either):
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", function () {
if (BrowserWindow.getAllWindows().length === 0) createWindow();
});
});
app.on("will-quit", (e) => {
console.log("App recieved request to quit");
e.preventDefault();
});
app.on("before-quit", (e) => {
console.log("App recieved request to quit");
e.preventDefault();
});
app.on("quit", (e) => {
console.log("App recieved request to quit");
e.preventDefault();
});
process.on("SIGINT SIGTERM", () => {
console.log("Detected SIGINT/SIGTERM");
});
process.on("SIGTERM", () => {
console.log("Detected SIGTERM");
});
This question concerns Linux only.
You're registering the event listeners too early. I modified your code to include all the listeners in the block after whenReady
and got the results you were expecting.