- Electron 教程
- Electron - 首頁
- Electron - 概述
- Electron - 安裝
- Electron 如何工作?
- Electron - Hello World
- Electron - 構建 UI
- Electron - 檔案處理
- Electron - 原生 Node 庫
- 程序間通訊 (IPC)
- Electron - 系統對話方塊
- Electron - 選單
- Electron - 系統托盤
- Electron - 通知
- Electron - Webview
- Electron - 音訊和影片捕獲
- Electron - 定義快捷方式
- Electron - 環境變數
- Electron - 除錯
- Electron - 打包應用
- Electron - 資源
- Electron 有用資源
- Electron - 快速指南
- Electron - 有用資源
- Electron - 討論
Electron - 通知
Electron 僅為 MacOS 提供原生通知 API。因此,我們不會使用該 API,而是會使用一個名為 node-notifier 的 npm 模組。它允許我們在 Windows、MacOS 和 Linux 上向用戶傳送通知。
使用以下命令在應用資料夾中安裝 node-notifier 模組 −
$ npm install --save node-notifier
現在讓我們建立一個有按鈕的應用,每當我們點選該按鈕時,它就會生成一條通知。
建立一個新的 main.js 檔案,並輸入以下程式碼 −
const {app, BrowserWindow} = require('electron')
const url = require('url')
const path = require('path')
let win
function createWindow() {
win = new BrowserWindow({width: 800, height: 600})
win.loadURL(url.format ({
pathname: path.join(__dirname, 'index.html'),
protocol: 'file:',
slashes: true
}))
}
app.on('ready', createWindow)
現在讓我們建立將觸發通知的網頁和指令碼。使用以下程式碼建立一個新的 index.html 檔案 −
<!DOCTYPE html>
<html>
<head>
<meta charset = "UTF-8">
<title>Menus</title>
</head>
<body>
<button type = "button" id = "notify" name = "button">
Click here to trigger a notification!</button>
<script type = "text/javascript">
const notifier = require('node-notifier')
const path = require('path');
document.getElementById('notify').onclick = (event) => {
notifier.notify ({
title: 'My awesome title',
message: 'Hello from electron, Mr. User!',
icon: path.join('','/home/ayushgp/Desktop/images.png'), // Absolute path
(doesn't work on balloons)
sound: true, // Only Notification Center or Windows Toasters
wait: true // Wait with callback, until user action is taken
against notification
}, function (err, response) {
// Response is response from notification
});
notifier.on('click', function (notifierObject, options) {
console.log("You clicked on the notification")
});
notifier.on('timeout', function (notifierObject, options) {
console.log("Notification timed out!")
});
}
</script>
</body>
</html>
notify 方法允許我們傳入一個 objectwith 資訊,如標題、訊息、縮圖等,這些資訊有助於我們自定義通知。我們還可以為通知設定一些事件偵聽器。
現在,使用以下命令執行該應用 −
$ electron ./main.js
當您點選我們建立的按鈕時,您將看到一個來自您作業系統的原生通知,如下圖所示 −
我們還處理了以下事件:使用者點選通知或通知超時。如果應用在後臺執行,這些方法有助於我們使應用更具互動性。
廣告