天天看點

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")