公司項目有一款帶即時聊天、群組功能的APP,因為要給客服人員使用,需要開發PC版本。之前使用C#開發過一個PC版本,但是C#的UI這一塊支持的不太好,而且升級比較麻煩,我就牽頭基於Electron去實現了一個PC版本。
遇到了客服那邊提過來的需求,當有新消息過來的時候,如果聊天窗口最小化了,需要有提醒,系統托盤也要像QQ一樣有新消息過來的提醒與閃爍。
查了一個資料,兩個功能都實現了。
先看任務欄的提醒樣式如何實現
const path = require('path'); const electron = require('electron'); const { app, BrowserWindow, Menu, ipcMain, Tray } = electron; let mainWnd = null; mainWnd = new BrowserWindow({ minWidth: 1200, minHeight: 750, resizable: true, icon: 'icon.ico', skipTaskbar: false });
// 開始或停止顯示窗口來獲得用戶的關注 mainWnd.flashFrame(true);
閃爍的原理就是,用定時器更換托盤圖標的icon,一張正常、一張透明,切換(像眨眼睛一樣)。
let appIcon = new Tray(iconPath); const contextMenu = Menu.buildFromTemplate([{ label: '移除', click: function() { event.sender.send('tray-removed'); } }, { type: 'separator' }, { label: 'Item1', type: 'radio' }, { type: 'separator' },{ label: 'MenuItem2', type: 'checkbox', checked: true }]); // Make a change to the context menu contextMenu.items[2].checked = false; appIcon.setToolTip('在托盤中的 Electron 示例.'); appIcon.setContextMenu(contextMenu); var count = 0; setInterval(function() { if (count++ % 2 == 0) { appIcon.setImage(path.join(__dirname, '../img/tray/tray_icon_2.png')); } else { appIcon.setImage(path.join(__dirname, '../img/tray/tray_icon.png')); } }, 400);
上面兩個功能並不復雜,主要是對API方法的調用。
參考:
[1] https://github.com/electron/electron/tree/master/docs-translations/zh-CN/api
[2] https://github.com/electron/electron/blob/master/docs-translations/zh-CN/api/browser-window.md
[3] https://github.com/electron/electron/blob/master/docs-translations/zh-CN/api/tray.md
[4] https://github.com/demopark/electron-api-demos-Zh_CN