问题
I am building an electron tray app for Mac OS. Everything seems okay, but if I run the app on one desktop and then switch to another, when I click on app icon, app returns me back to place where it was launched. How can I fix it to be open on every desktop? Thanks in advance
// Sets variables (const)
const {app, BrowserWindow, ipcMain, Tray} = require('electron')
const path = require('path')
const assetsDirectory = path.join(__dirname, 'img')
let tray = undefined
let window = undefined
// Don't show the app in the doc
app.dock.hide()
// Creates tray & window
app.on('ready', () => {
createTray()
createWindow()
})
// Quit the app when the window is closed
app.on('window-all-closed', () => {
app.quit()
})
// Creates tray image & toggles window on click
const createTray = () => {
tray = new Tray(path.join(assetsDirectory, 'icon.png'))
tray.on('click', function (event) {
toggleWindow()
})
}
const getWindowPosition = () => {
const windowBounds = window.getBounds()
const trayBounds = tray.getBounds()
// Center window horizontally below the tray icon
const x = Math.round(trayBounds.x + (trayBounds.width / 2) - (windowBounds.width / 2))
// Position window 4 pixels vertically below the tray icon
const y = Math.round(trayBounds.y + trayBounds.height + 3)
return {x: x, y: y}
}
// Creates window & specifies its values
const createWindow = () => {
window = new BrowserWindow({
width: 250,
height: 310,
show: false,
frame: false,
fullscreenable: false,
resizable: false,
transparent: true,
'node-integration': false
})
// This is where the index.html file is loaded into the window
window.loadURL('file://' + __dirname + '/index.html');
// Hide the window when it loses focus
window.on('blur', () => {
if (!window.webContents.isDevToolsOpened()) {
window.hide()
}
})
}
const toggleWindow = () => {
if (window.isVisible()) {
window.hide()
} else {
showWindow()
}
}
const showWindow = () => {
const position = getWindowPosition()
window.setPosition(position.x, position.y, false)
window.show()
window.focus()
}
ipcMain.on('show-window', () => {
showWindow()
})
回答1:
You can either call win.setVisibleOnAllWorkspaces(true); or call app.dock.hide();
win.setVisibleOnAllWorkspaces(true); Does what it says and makes the window visible on all workspaces.
app.dock.hide(); Hides the dock icon for your application but will allow all windows in your application to be visible on all workspaces.
I think in your case you should go with win.setVisibleOnAllWorkspaces(true);
win.setVisibleOnAllWorkspaces();
https://electron.atom.io/docs/api/browser-window/#winsetvisibleonallworkspacesvisible
app.dock.hide();
https://electron.atom.io/docs/api/app/#appdockhide-macos
来源:https://stackoverflow.com/questions/45268762/electron-tray-app-position-on-mac-os