Skip to content

Instantly share code, notes, and snippets.

@hyrious
Created January 24, 2019 09:47
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save hyrious/b76b3a1042907421feb68261f505f0eb to your computer and use it in GitHub Desktop.
Save hyrious/b76b3a1042907421feb68261f505f0eb to your computer and use it in GitHub Desktop.
electron exit to tray
const {
app,
BrowserWindow,
Menu,
Tray,
nativeImage,
ipcMain
} = require("electron");
let win, tray;
const createWindow = () => {
win = new BrowserWindow({ width: 200, height: 200, show: false });
win.once("ready-to-show", () => win.show());
win.on("closed", () => (win = null));
tray = new Tray(nativeImage.createEmpty());
tray.setToolTip("el-pg");
const contextMenu = Menu.buildFromTemplate([
{
label: "Show",
type: "normal",
click() {
win.show();
}
},
{ label: "Exit", type: "normal", role: "quit" }
]);
tray.on("click", () => (win.isVisible() ? win.hide() : win.show()));
tray.setContextMenu(contextMenu);
win.on("close", e => {
if (win.isVisible()) {
win.hide();
e.preventDefault();
}
});
win.loadFile("index.html");
};
app.on("ready", createWindow);
app.on("activate", () => {
if (win == null) createWindow();
});
app.on("window-all-closed", () => {
if (process.playform !== "darwin") app.quit();
});
/*
<script>
const { ipcRenderer } = require('electron');
function send(arg) {
ipcRenderer.send('asynchronous-message', arg);
}
</script>
<button onclick="send('tray')">win.hide();</button>
<button onclick="send('quit')">app.quit();</button>
*/
ipcMain.on("asynchronous-message", (event, arg) => {
if (arg === "tray") win.hide();
if (arg === "quit") app.quit();
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment