基於electron開發MacOS Menubar app主要涉及的技術其實就是Electron的 Tray API。javascript
此外也有人將這個API作了簡單的封裝:menubar(github) 。java
其基本原理就是將Electron的窗口挪到menubar對應app按鈕的下面,也就是點擊menu bar按鈕時,在獲取按鈕的位置,而後在按鈕的下方顯示窗口。git
好比在這裏有一個將傳統Electron改造爲MacOS Menubar application的例子:github
// 檢測是否MacOS darwin if (platform === 'darwin' || tray) { const iconPath = join(__dirname, 'static/IconTrayMac.png'); const trayIcon = new Tray(iconPath); trayIcon.setToolTip(`${app.getName()}`); // 點擊時顯示窗口,並修改窗口的顯示位置 trayIcon.on('click', () => { const {screen} = electron; const {width, height} = screen.getPrimaryDisplay().workAreaSize; const [defaultWidth, defaultHeight] = [width, height].map(x => Math.round((x * 3) / 4)); const WINDOW_WIDTH = defaultWidth - 350; const WINDOW_HEIGHT = defaultHeight; const HORIZ_PADDING = 15; const VERT_PADDING = 15; const cursorPosition = screen.getCursorScreenPoint(); const primarySize = screen.getPrimaryDisplay().workAreaSize; const trayPositionVert = cursorPosition.y >= primarySize.height / 2 ? 'bottom' : 'top'; const trayPositionHoriz = cursorPosition.x >= primarySize.width / 2 ? 'right' : 'left'; win.setPosition(getTrayPosX(), getTrayPosY()); if (win.isVisible()) { win.hide(); } else { win.show(); } // 計算位置 function getTrayPosX() { const horizBounds = { left: cursorPosition.x - (WINDOW_WIDTH / 2), right: cursorPosition.x + (WINDOW_WIDTH / 2) }; if (trayPositionHoriz === 'left') { return horizBounds.left <= HORIZ_PADDING ? HORIZ_PADDING : horizBounds.left; } return horizBounds.right >= primarySize.width ? primarySize.width - HORIZ_PADDING - WINDOW_WIDTH : horizBounds.right - WINDOW_WIDTH; } function getTrayPosY() { return trayPositionVert === 'bottom' ? cursorPosition.y - WINDOW_HEIGHT - VERT_PADDING : cursorPosition.y + VERT_PADDING; } }); return; }
這個時候就有了效果:npm
接下來還有一個問題,就是怎麼實現 點擊其餘地方時,該窗口自動隱藏 。
這裏要用到的是Electron的 Blur 事件(文檔):api
aoWindow.on('blur', () => { if (platform === 'darwin') { aoWindow.hide(); } });
在MacOS系統中,檢測到Blur事件,也就是未聚焦於窗口時,調用 hide
把窗口隱藏掉。app
這樣,就實現了一個MacOS的Menubar application!electron
接下來就用 electron-packager
將該App打包成MacOS的dmg包就好了!ide
Tips:
使用electron-packager
打包過程有個坑,就是使用cnpm安裝依賴的話,會致使打包時間極爲漫長,用npm從新安裝就行了。Tips:
用於MacOS中Tray的icon,有個經驗是將icon大小設置爲14X14。spa
最後給出一個我Fork後修改的Github開源Microsoft To-Do desktop app應用的地址:https://github.com/Anderson-L...
原repo地址:https://github.com/klauscfhq/ao
界面頗有設計感,通過改造爲Menubar app後效率更是大幅提高!