メインコンテンツへ飛ぶ

Notification

デスクトップ通知を作成します。

プロセス: メイン

[!NOTE] レンダラープロセスから通知を表示したい場合は、ウェブの Notification API を使用する必要があります。

[!NOTE] macOS では、通知は基盤となるフレームワークとして UNNotification API を使用します。この API では、通知を表示するために、 アプリケーションがコード署名されている必要があります。署名されていないバイナリーでは、通知を呼び出すと failed イベントが発生します。

クラス: Notification​

デスクトップ通知を作成します。

プロセス: メイン

Notification は EventEmitter を継承しています。

options によって設定されたネイティブプロパティで新しい Notification を生成します。

[!WARNING] Electron 組み込みのクラスはユーザコードでサブクラス化できません。詳細については、FAQ をご参照ください。

静的メソッド​

Notification クラスには、次の静的メソッドがあります。

Notification.isSupported()​

戻り値 boolean - 現在のシステムでデスクトップ通知がサポートされているかどうか。

Notification.handleActivation(callback) Windows​

  • callback Function

すべての通知のアクティベーションを処理するコールバックを登録します。このコールバックは、元の Notification オブジェクトがまだメモリー上にあるかどうかに関わらず、 通知がクリックされたとき、返信されたとき、 またはアクションボタンが押されたときに呼び出されます。

このメソッドはタイミングを自動的に処理します。

  • このメソッドを呼び出す前にすでにアクティベーションが発生していた場合、 コールバックはその詳細とともに直ちに呼び出されます。
  • それ以降のすべてのアクティベーションについては、発生時にコールバックが呼び出されます。

コールバックは、別の handleActivation の呼び出しで置き換えられるまで登録されたままになります。

これにより、あらゆるシナリオで機能する、通知の操作を一元的に処理する方法が提供されます。

  • コールドスタート (通知のクリックからアプリが起動された場合)
  • アプリの再起動後にメモリー上の表現を持たない、アクションセンターに残っている通知
  • Notification オブジェクトがガベージコレクトされた
  • Notification オブジェクトがまだメモリー上にある (インスタンスイベントに加えてコールバックも呼び出される)
const { Notification, app } = require('electron')

app.whenReady().then(() => {
// すべての通知のアクティベーションに対するハンドラーを登録します
Notification.handleActivation((details) => {
console.log('Notification activated:', details.type)
if (details.type === 'reply') {
console.log('User reply:', details.reply)
} else if (details.type === 'action') {
console.log('Action index:', details.actionIndex)
}
})
})

Notification.getHistory() macOS​

戻り値 Promise<Notification[]> - 通知センターにまだ残っている、配信済みのすべての通知を表す Notification オブジェクトの配列で解決されます。

返される各 Notification は、対応する配信済み通知に接続されたライブオブジェクトです。ユーザーが通知センターで通知を操作すると、これらのオブジェクトで操作イベント (click、reply、action、close) が発生します。これは、アプリの再起動後に、以前のセッションの通知にイベントハンドラーを再びアタッチする場合に便利です。

返される通知の id、groupId、title、subtitle、body プロパティには、通知センターで利用可能な情報が設定されます。その他のプロパティ (例: actions、silent、icon) は配信済みの通知からは取得できず、デフォルト値になります。

[!NOTE] 他のすべての macOS 通知 API と同様に、 このメソッドではアプリケーションがコード署名されている必要があります。署名されていない開発ビルドでは、通知は通知センターに配信されず、 このメソッドは空の配列で解決されます。

注釈

new Notification() で作成された通知とは異なり、 getHistory() が返す通知は、オブジェクトがガベージコレクトされた後も、 通知センターに表示されたままになります。復元された通知で show() を呼び出すと、 元の通知が通知センターから削除され、 同じプロパティを持つ新しい通知が投稿されます。

const { Notification, app } = require('electron')

app.whenReady().then(async () => {
// 以前のセッションの通知を復元します
const notifications = await Notification.getHistory()
for (const n of notifications) {
console.log(`Found delivered notification: ${n.id} - ${n.title}`)
n.on('click', () => {
console.log(`User clicked: ${n.id}`)
})
n.on('reply', (event) => {
console.log(`User replied to ${n.id}: ${event.reply}`)
})
}
// イベントが発生し続けるよう参照を保持します
})

Notification.remove(id) macOS​

1 つ以上の配信済み通知を、その識別子によって通知センターから削除します。

const { Notification } = require('electron')

// 単一の通知を削除します
Notification.remove('my-notification-id')

// 複数の通知を削除します
Notification.remove(['msg-1', 'msg-2', 'msg-3'])

Notification.removeAll() macOS​

アプリの配信済みの通知をすべて通知センターから削除します。

const { Notification } = require('electron')

Notification.removeAll()

Notification.removeGroup(groupId) macOS​

指定された groupId を持つ配信済みの通知をすべて通知センターから削除します。

const { Notification } = require('electron')

// 'chat-thread-1' グループ内のすべての通知を削除します
Notification.removeGroup('chat-thread-1')

new Notification([options])​

  • options Object (任意)
    • id string (任意) macOS Windows - 通知の一意の識別子。 macOS では、UNNotificationRequest の identifier プロパティに対応します。 Windows では、トースト通知の Tag プロパティに対応します。指定されなかった場合や空文字列が渡された場合の省略値は、ランダムな UUID です。特定の配信済み通知を削除するには Notification.remove() で、それらを識別するには Notification.getHistory() で、この識別子を使用します。
    • groupId string (任意) macOS Windows - 通知センター / アクションセンターで通知を視覚的にグループ化するために使用される文字列の識別子。 macOS では、UNNotificationContent の threadIdentifier プロパティに対応します。 Windows では、トースト通知の Group プロパティに対応します。グループ内のすべての通知を削除するには、この識別子を Notification.removeGroup() で使用します。
    • groupTitle string (任意) Windows - 通知グループのヘッダーのタイトル。 groupId と groupTitle の両方が指定されている場合、Windows は関連する通知をまとめるヘッダーを通知の上に表示します。トースト通知の header 要素に対応します。
    • title string (任意) - 通知ウィンドウの上部に表示される通知のタイトルです。
    • subtitle string (任意) macOS - タイトルの下に表示される、通知のサブタイトル。
    • body string (任意) - タイトルやサブタイトルの下に表示さる、通知の本文。
    • silent boolean (任意) - 通知を表示するときに OS が通知音を鳴らさないかどうか。
    • icon (string | NativeImage) (任意) - 通知に使用するアイコン。文字列を渡す場合、ローカルのアイコンファイルへの有効なパスでなければなりません。
    • hasReply boolean (任意) macOS Windows - 通知にインライン返信オプションを追加するかどうか。
    • timeoutType string (任意) Linux Windows - 通知の消失までの時間。 'default' か 'never' にできます。
    • replyPlaceholder string (任意) macOS Windows - インライン返信の入力フィールドに表示するプレースホルダー。
    • sound string (任意) macOS - 通知が表示されるときに再生される音声ファイルの名前。
    • urgency string (任意) Linux Windows - 通知の緊急度。 'normal'、'critical'、'low' のいずれかにできます。
    • actions NotificationAction[] (任意) - 通知に追加するアクション。 NotificationAction ドキュメント内の有効なアクションと制限を読んで下さい。
    • closeButtonText string (任意) macOS - 通知を閉じるボタンのカスタムタイトル。空の文字列の場合は、既定のローカライズされたテキストが使用されます。
    • toastXml string (任意) Windows - Windows 通知のカスタム記述は、上記のプロパティすべてを上書きします。これは通知のデザインと動作の完全なカスタマイズを提供します。

[!NOTE] Windows では、urgency の種類を 'critical' にすると、アクションセンター内で通知がより上位 (デフォルトの優先度の通知より上) に並べられますが、自動的に消えるのは防げません。自動的に消えるのを防ぐには、 timeoutType も 'never' に設定してください。

インスタンスイベント​

new Notification で作成されたオブジェクトでは以下のイベントが発生します。

情報

いくつかのイベントは特定のオペレーティングシステムでのみ利用可能で、そのように注記がつけられています。

イベント: 'show'​

戻り値:

  • event Event

ユーザに通知が表示されると発行されます。注意として、通知は show() メソッドを介すると複数回表示できるので、このイベントは複数回起こることがあります。

const { Notification, app } = require('electron')

app.whenReady().then(() => {
const n = new Notification({
title: 'Title!',
subtitle: 'Subtitle!',
body: 'Body!'
})

n.on('show', () => console.log('Notification shown!'))

n.show()
})

イベント: 'click'​

戻り値:

  • event Event

ユーザによって通知がクリックされたときに発行されます。

const { Notification, app } = require('electron')

app.whenReady().then(() => {
const n = new Notification({
title: 'Title!',
subtitle: 'Subtitle!',
body: 'Body!'
})

n.on('click', () => console.log('Notification clicked!'))

n.show()
})

イベント: 'close'​

戻り値:

  • details Event<>
    • reason Windows string (任意) - 通知が閉じられた理由。 'userCanceled'、'applicationHidden'、'timedOut' のいずれかになります。

ユーザの手によって手動で通知が閉じられたときに発行されます。

このイベントは、通知が閉じられたすべての状況で発行されることは保証されていません。

Windows 上では、この close イベントは次の 3 つの方法のうちのいずれかで発生する可能性があります。notification.close() によるプログラムでの解除、ユーザーが通知を閉じることによる解除、またはシステムタイムアウトによる解除です。最初の close イベントが発行された後に通知がアクションセンターにある場合、notification.close() を呼び出すとアクションセンターから通知が削除されますが、これによって close イベントが再び発生することはありません。

const { Notification, app } = require('electron')

app.whenReady().then(() => {
const n = new Notification({
title: 'Title!',
subtitle: 'Subtitle!',
body: 'Body!'
})

n.on('close', () => console.log('Notification closed!'))

n.show()
})

イベント: 'reply' macOS Windows​

戻り値:

  • details Event<>
    • reply string - ユーザが埋め込み返信フィールドに入力した文字列.
  • reply string 非推奨

hasReply: true の通知上で、ユーザが "返信" ボタンをクリックしたときに発行されます。

const { Notification, app } = require('electron')

app.whenReady().then(() => {
const n = new Notification({
title: 'Send a Message',
body: 'Body Text',
hasReply: true,
replyPlaceholder: 'Message text...'
})

n.on('reply', (e, reply) => console.log(`User replied: ${reply}`))
n.on('click', () => console.log('Notification clicked'))

n.show()
})

イベント: 'action'​

戻り値:

  • details Event<>
    • actionIndex number - アクティベートされたアクションのインデックス.
    • selectionIndex number Windows - アイテムが選択された場合、選択されたアイテムのインデックス。何も選択されなかった場合は -1。
  • actionIndex number 非推奨
  • selectionIndex number Windows 非推奨
const { Notification, app } = require('electron')

app.whenReady().then(() => {
const items = ['One', 'Two', 'Three']
const n = new Notification({
title: 'Choose an Action!',
actions: [
{ type: 'button', text: 'Action 1' },
{ type: 'button', text: 'Action 2' },
{ type: 'selection', text: 'Apply', items }
]
})

n.on('click', () => console.log('Notification clicked'))
n.on('action', (e) => {
console.log(`User triggered action at index: ${e.actionIndex}`)
if (e.selectionIndex > -1) {
console.log(`User chose selection item '${items[e.selectionIndex]}'`)
}
})

n.show()
})

イベント: 'failed' macOS Windows​

戻り値:

  • event Event
  • error string - show() メソッドの実行中に発生したエラー。

ネイティブ通知の作成および表示でエラーに遭遇した場合に発生します。

const { Notification, app } = require('electron')

app.whenReady().then(() => {
const n = new Notification({
title: 'Bad Action'
})

n.on('failed', (e, err) => {
console.log('Notification failed: ', err)
})

n.show()
})

インスタンスメソッド​

new Notification() コンストラクタで作成されたオブジェクトは、次のインスタンスメソッドを持っています。

notification.show()​

即座にユーザーに通知を表示します。ウェブの Notification API とは異なり、new Notification() とインスタンス化するだけではユーザに即座に表示されません。そこで代わりに、OS が表示する前にこのメソッドを呼び出す必要があります。

以前にその通知が表示されている場合、このメソッドはその通知を閉じ、同じプロパティを持つ新しい通知を作成します。

macOS では、Notification.getHistory() が返した通知で show() を呼び出すと、 元の通知が通知センターから削除され、 同じプロパティを持つ新しい通知が投稿されます。

const { Notification, app } = require('electron')

app.whenReady().then(() => {
const n = new Notification({
title: 'Title!',
subtitle: 'Subtitle!',
body: 'Body!'
})

n.show()
})

notification.close()​

通知を閉じます。

Windows では、通知が画面に表示されている間に notification.close() を呼び出すと、通知が解除され、アクションセンターから削除されます。もし通知が画面上に通知が表示されなくなってから notification.close() を呼び出した場合、notification.close() はアクションセンターから通知を削除しようとします。

const { Notification, app } = require('electron')

app.whenReady().then(() => {
const n = new Notification({
title: 'Title!',
subtitle: 'Subtitle!',
body: 'Body!'
})

n.show()

setTimeout(() => n.close(), 5000)
})

インスタンスプロパティ​

notification.id macOS Windows Readonly​

通知の一意の識別子を表す string プロパティ。これは構築時に設定されます。id オプションから設定されるか、指定されなかった場合は生成された UUID になります。

notification.groupId macOS Windows Readonly​

通知のグループ識別子を表す string プロパティ。同じ groupId を持つ通知は、通知センター (macOS) またはアクションセンター (Windows) で視覚的にグループ化されます。

notification.groupTitle Windows Readonly​

通知グループのヘッダーのタイトルを表す string プロパティ。

notification.title​

通知のタイトルを表す string プロパティ。

notification.subtitle​

通知のサブタイトルを表す string プロパティ。

notification.body​

通知の本文を表す string プロパティ。

notification.replyPlaceholder​

通知の応答プレースホルダーを表す string プロパティ。

notification.sound​

通知音を表す string プロパティ。

notification.closeButtonText​

通知の閉じるボタンのテキストを表す string プロパティ。

notification.silent​

通知が無音かどうかを表す boolean プロパティ。

notification.hasReply​

通知に応答アクションがあるかどうかを表す boolean プロパティ。

notification.urgency Linux​

通知の緊急度を表す string プロパティ。 'normal'、'critical'、'low' のいずれかにできます。

省略値は 'low' です。詳細は NotifyUrgency をご参照ください。

notification.timeoutType Linux Windows​

通知がタイムアウトする種別を表す string プロパティ。 'default' か 'never' にできます。

timeoutType が 'never' に設定されている場合、通知は自動的に閉じられません。呼び出し元の API かユーザによって閉じられるまで開いたままになります。

notification.actions​

NotificationAction[] 型のプロパティで、通知のアクションを表します。

notification.toastXml Windows​

string 型のプロパティで、通知のカスタム Toast XML を表します。

サウンドの再生​

macOS では、通知が表示されたときに再生したいサウンドの名前を指定することができます。カスタムサウンドファイルに加えて、(システム環境設定 > サウンド にある) デフォルトサウンドのいずれかを使用することができます。サウンドファイルがアプリバンドル (YourApp.app/Contents/Resources など) または以下のいずれかの場所にコピーされることに留意してください。

  • ~/ライブラリ/Sounds
  • /ライブラリ/Sounds
  • /ネットワーク/ライブラリ/Sounds
  • /システム/ライブラリ/Sounds

より詳しくは NSSound のドキュメントをご参照ください。