天天看点

electron实现消息闪烁,与页面通信

根目录下新建vue.config.js
module.exports = {
  pluginOptions: {
    electronBuilder: {
      nodeIntegration: true,
      builderOptions: {
        win: {
          icon: "./public/app.ico", // 自行切换
        },
        mac: {
          icon: "./public/app.png", // 自行切换
        },
      },
    },
  },
};
           
// background.js (只粘贴相关部分,其他的功能自行添加)
import { app, protocol, BrowserWindow, Tray, ipcMain } from "electron";

const path = require("path");  // 图片放在public文件夹
let trayIcon = path.join(__dirname, "../public"); 
let appIcon = path.join(trayIcon, "app.png");  // app logo
let emptyIcon = path.join(trayIcon, "empty.png");  //  空白图
           

不会制作透明ico图标的可以下面链接下载:

点击打开链接

// background.js
async function createWindow() {
	const win = new BrowserWindow({
    width: 1200,
    height: 620,
    webPreferences: {
      nodeIntegration: process.env.ELECTRON_NODE_INTEGRATION,
      contextIsolation: !process.env.ELECTRON_NODE_INTEGRATION,
    },
    icon: `${__static / app.ico}`,
    skipTaskbar: false,
    resizable: true,
  });

	// 开始或停止显示窗口来获得用户的关注
  	win.flashFrame(true);
 	let appTray = new Tray(path.join(trayIcon, "app.png"));
  	let flashTrayTimer = null; // 定时器

   // 托盘图标闪烁
   function flashTray(flash) {
     let hasIco = false;
     if (flash) {
       if (flashTrayTimer) return;
       flashTrayTimer = setInterval(() => {
         appTray.setImage(hasIco ? appIcon : emptyIcon);
         hasIco = !hasIco;
       }, 500);
     } else {
       if (flashTrayTimer) {
         clearInterval(flashTrayTimer);
         flashTrayTimer = null;
       }
       appTray.setImage(appIcon);
     }
   }
   
   // 消息来,与页面通信, 事件名news可自定义
   ipcMain.on("news", () => {
     flashTray(true);  // false可取消闪烁
   });
}
           

页面组件中与electron通信,例如有消息推送闪烁图标:

// App.vue
// 引入ipc
const ipc = window.require ? window.require("electron").ipcRenderer : null; 
// 需要通信时,使用send发送
ipc && ipc.send("news")