electron实现类似于微信来消息图标闪烁功能
闪烁其实是图标与空白图标来回切换,直接上代码
main.js里的代码:
import {
app,
BrowserWindow,
ipcMain,
Tray,
Menu
} from "electron";
//需要操作的页面,一般为消息列表页面
let home_win = new BrowserWindow({
width: 300,
height: 710,
maxWidth: 350,
minWidth: 288,
frame: false, //是否带工具栏
resizable: false,
webPreferences: {
webSecurity: false //是否禁用同源策略(上线时删除此配置)
}
});
/**
* 托盘图标事件
*/
let flashTrayTimer = null
let trayIco1 = `${__static}/imgs/logo.png` //logo图标
let trayIco2 = `${__static}/imgs/empty.ico` //隐藏logo换上的空白图标
let apptray = {
// 创建托盘图标
createTray() {
tray = new Tray(trayIco1)
const menu = Menu.buildFromTemplate([{
label: '打开主界面', //图标点击右键的菜单
click: () => {
if (home_win) {
home_win.restore()
home_win.show()
home_win.focus()
}
this.flashTray(false) //图标停止闪烁
}
},
{
label: '关于',
},
{
label: '退出',
click: () => {
if (process.platform !== 'darwin') {
if (home_win) {
// home_win.show()
// 清空登录信息
home_win.webContents.send('clearLoggedInfo')
forceQuit = true
home_win = null
}
app.quit()
}
}
},
])
tray.setContextMenu(menu)
tray.setToolTip('自定义')
// 托盘点击事件
tray.on('click', () => {
global.isHide = false
if (home_win) {
if (home_win.isMinimized())
home_win.restore()
home_win.show() //显示
home_win.focus() //获取焦点
// this.flashTray(false)
}
})
// 消息来,图标闪烁
//let isMix = global.isHide //用来判断图标是否隐藏与系统托盘
const ipc = require('electron').ipcMain
//与页面通信
ipc.on('news', () => {
if (!home_win.isFocused()||global.isHide) {
this.flashTray(true)
}
})
ipc.on('flashfalse',()=>{ //这几个事件我是为了在其它页面时,消息来了图标也能闪烁
this.flashTray(false)
global.isHide=false
})
ipc.on('flashtrue',()=>{
global.isHide=true
})
ipc.on('mini', () => {
global.isHide = true
home_win.hide() //页面隐藏到托盘
})
//消息来了弹框处理
//ipc.on('msgclick', () => {
//global.isHide = false
//if (home_win) {
//if (home_win.isMinimized())
//home_win.restore()
//home_win.show()
//home_win.focus()
// this.flashTray(false)
// }
//})
},
// 托盘图标闪烁
flashTray(flash) {
let hasIco = false
if (flash) {
if (flashTrayTimer) return
flashTrayTimer = setInterval(() => {
tray.setImage(hasIco ? trayIco1 : trayIco2)
hasIco = !hasIco
}, 500)
} else {
if (flashTrayTimer) {
clearInterval(flashTrayTimer)
flashTrayTimer = null
}
tray.setImage(trayIco1)
}
},
下面是vue里建立与main.js代码通信代码的实现
webscocet(下一篇是它)里当消息来了的时候,加上以下代码,可以调用main.js的ipc.on事件
const ipc = require("electron").ipcRenderer;
ipc.send("news");
我是菜狗,如有更好的办法,欢迎大家交流