nwjs桌面端实现托盘闪动及托盘菜单操作

558 阅读1分钟
'use strict'

const gui = window.require('nw.gui')
const win = gui.Window.get()
let isShowWindow = true
window.sharkFlag = false
let isDefault = true
// var trayIconIntervalSymbol = null
// 主界面显示/隐藏切换
export function toggleWinShowHide () {
  if (isShowWindow) {
    win.hide()
    isShowWindow = false
  } else {
    win.show()
    isShowWindow = true
  }
}

// 退出至登录界面
export function exitToLogin () {
  win.show()
  let customEvent = new CustomEvent('bridgePCAndWeb', {
    detail: 'EXITTRAYMENU'
  })
  document.dispatchEvent(customEvent)
}

// 打开设置界面
export function openConfigWindow () {
  win.show()
  let customEvent = new CustomEvent('bridgePCAndWeb', {
    detail: 'SETTINGTRAYMENU'
  })
  document.dispatchEvent(customEvent)
}

// 创建新托盘
export function createNewTray () {
  let tray = new gui.Tray({title: '我的应用', icon: '/static/im/tray-logo-default.png', alticon: '/static/im/tray-logo-alt.png'})
  tray.on('click', () => {
    window.sharkFlag = false
    window.toggleFlag = false
    win.show()
    setTimeout(() => {
      win.requestAttention(true)
    }, 1000)
    win.setShadow(true)
    // initTrayIcon(window.tray)
  })
  return tray
}

// 动态切换托盘icon,托盘闪动
export function toggleTrayIcon (tray) {
  if (!window.sharkFlag || !window.hideFlag) {
    isDefault = true
    window.toggleFlag = false
    changeTrayIcon(tray, '/static/im/tray-logo-default.png')
    return
  }
  window.toggleFlag = true
  setTimeout(() => {
    if (isDefault) {
      isDefault = false
      changeTrayIcon(tray, '/static/im/tray-logo-default.png')
      toggleTrayIcon(tray)
    } else {
      isDefault = true
      changeTrayIcon(tray, '/static/im/tray-logo-alt.png')
      toggleTrayIcon(tray)
    }
  }, 350)
}

// 初始化托盘icon
export function initTrayIcon (tray) {
  window.sharkFlag = false
  changeTrayIcon(tray, '/static/im/tray-logo-default.png')
}

// 为托盘新建目录
export function createNewTrayMenu (tray) {
  var menu = new gui.Menu()
  menu.append(new gui.MenuItem({
    type: 'normal',
    label: '主界面',
    click: () => {
      win.show()
      win.requestAttention(true)
    }
  }))
  menu.append(new gui.MenuItem({type: 'normal', label: '设置', click: openConfigWindow}))
  menu.append(new gui.MenuItem({type: 'separator'}))
  menu.append(new gui.MenuItem({type: 'normal', label: '退出', click: exitToLogin}))
  tray.menu = menu
  return tray
}

// 修改托盘图标
export function changeTrayIcon (tray, icon) {
  tray.icon = icon
  return tray
}

// 删除托盘
export function removeTray (tray) {
  tray.remove()
}
// 系统托盘官网文档:http://docs.nwjs.io/en/latest/References/Tray/
// 系统托盘中文文档:https://nwjs.org.cn/doc/api/Tray.html
// 参考文章:https://www.cnblogs.com/lfm601508022/p/10719658.html