目录

电子 - 通知( Notifications)

Electron仅为MacOS提供本机通知API。 所以我们不打算使用它,而是使用名为node-notifier的npm模块。 它允许我们在Windows,MacOS和Linux上通知用户。

使用该文件夹中的以下命令在app文件夹中安装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

当您单击我们创建的按钮时,您将看到来自操作系统的本机通知,如以下屏幕截图所示 -

通知

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

↑回到顶部↑
WIKI教程 @2018