electron-tests/main.js

71 lines
1.4 KiB
JavaScript

const { app, BrowserWindow, Menu, Tray } = require('electron');
const path = require('path');
let tray = null;
let mainWindow = null;
function createWindow() {
mainWindow = new BrowserWindow({
width: 700,
height: 420,
title: 'Electron Tray Demo',
webPreferences: {
contextIsolation: true,
nodeIntegration: false,
},
});
mainWindow.loadFile(path.join(__dirname, 'index.html'));
mainWindow.on('close', (event) => {
if (!app.isQuiting) {
event.preventDefault();
mainWindow.hide();
}
});
}
function createTray() {
const iconPath = path.join(__dirname, 'assets', 'trayTemplate.png');
tray = new Tray(iconPath);
tray.setToolTip('Electron Tray Demo');
const contextMenu = Menu.buildFromTemplate([
{
label: 'Show Window',
click: () => {
if (mainWindow) {
mainWindow.show();
mainWindow.focus();
}
},
},
{
label: 'Quit',
click: () => {
app.isQuiting = true;
app.quit();
},
},
]);
tray.setContextMenu(contextMenu);
tray.on('double-click', () => {
if (mainWindow) {
mainWindow.show();
mainWindow.focus();
}
});
}
app.whenReady().then(() => {
createWindow();
createTray();
app.on('activate', () => {
if (BrowserWindow.getAllWindows().length === 0) createWindow();
});
});
app.on('window-all-closed', () => {
// keep tray app alive on Linux/macOS
});