Electron-notifications
提供:Dev Guides
電子-通知
Electronは、MacOS専用のネイティブ通知APIを提供します。 そのため、これを使用するのではなく、_node-notifier_というnpmモジュールを使用します。 Windows、MacOS、Linuxのユーザーに通知できます。
そのフォルダで次のコマンドを使用して、アプリフォルダにノード通知モジュールをインストールします-
$ 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, 'indexl'),
protocol: 'file:',
slashes: true
}))
}
app.on('ready', createWindow)
次に、通知をトリガーするWebページとスクリプトを作成しましょう。 次のコードで新しい indexl ファイルを作成します-
<!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
作成したボタンをクリックすると、次のスクリーンショットに示すように、オペレーティングシステムからのネイティブ通知が表示されます-
また、ユーザーが通知をクリックするか、通知がタイムアウトするイベントも処理しました。 これらのメソッドは、アプリがバックグラウンドで実行されている場合、アプリをよりインタラクティブにするのに役立ちます。