How to open a new window from tray icon of electron
Currently I am trying to create a window widget. I faced 3 problems.
- It was successful until creating a checkbox in the Tray icon right-click menu. But I want to show a new window when the checkbox is clicked. (Because I want to make a settings menu)
I tried to open a new window on the Tray icon, but it was difficult to understand because there was a lot of outdated information using 'remote'. (Remote is currently deprecated. https://www.electronjs.org/docs/api/remote)
For the second question, I made 'always on top' in the right-click menu of the tray icon, but it doesn't work.
I want to add the process of remembering the window position when the app is closed and restoring the coordinates when starting the app, but an error occurs.
const {app, BrowserWindow, Menu, Tray} = require('electron')
const path = require('path')
const url = require('url')
// Multiple execution prevention
const doubleboot = app.requestSingleInstanceLock();
if(!doubleboot){
app.quit();
}
let win
function createWindow () {
// Create the browser window.
win = new BrowserWindow({
width: 800,
height: 600,
transparent:true,
frame:false,
resizable:false,
webPreferences: {
nodeIntegration: true,
},
alwaysOnTop : false,
})
// and load the index.html of the app.
win.loadURL(url.format({
pathname: path.join(__dirname, 'index.html'),
protocol: 'file:',
slashes: true
}))
// Open the DevTools.
win.webContents.openDevTools()
// Restore window position
if (localStorage.getItem("windowPosition")) {
var pos = JSON.parse(localStorage.getItem("windowPosition"));
win.setPosition(pos[0], pos[1]);
}
// Emitted when the window is closed.
win.on('closed', function () {
// Dereference the window object, usually you would store windows
// in an array if your app supports multi windows, this is the time
// when you should delete the corresponding element.
// win = null
// Save window position when closed
localStorage.setItem("windowPosition", JSON.stringify(win.getPosition()));
})
}
// https://www.electronjs.org/docs/api/tray
app.whenReady().then(() => {
tray = new Tray('./img/icon.ico')
const contextMenu = Menu.buildFromTemplate([
{ label: 'Always on top', type: 'checkbox'},
{ label: "Focus", click: function () { win.focus(); } },
{ label: 'Settings', click: function () { window.open()} },
{ label: "Exit", click: function () { win.close(); } }
])
tray.setToolTip('This is my application.')
tray.setContextMenu(contextMenu)
contextMenu.items[0].checked = false
//always on top
function checked(){
if (contextMenu.items[0] === 0 ){
win.alwaysOnTop = true;
}
else {
win.alwaysOnTop = false;
}
}
})
app.on('ready', createWindow)
// app.on('window-all-closed', () => {
// if (process.platform !== 'darwin') {
// app.quit()
// }
// })
// app.on('activate', () => {
// if (win === null) {
// createWindow()
// }
// })