Electron 教程:通知
Electron只为MacOS提供本地通知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方法允许我们向它传递一个带有信息的对象,如标题、消息、缩略图等。这有助于我们定制通知。我们还可以在通知上设置一些事件监听器。
现在,使用以下命令运行应用程序
$ electron ./main.js
当您单击页面上的按钮时,您将看到来自操作系统的通知,如下图所示.

我们还处理了用户点击通知或通知超时的事件。这些方法帮助我们使应用程序在后台运行时更具交互性。