メインコンテンツへ飛ぶ

Notification

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

プロセス: メイン

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

[!NOTE] On MacOS, notifications use the UNNotification API as their underlying framework. This API requires an application to be code-signed in order for notifications to appear. Unsigned binaries will emit a failed event when notifications are called.

クラス: Notification

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

プロセス: メイン

NotificationEventEmitter を継承しています。

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

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

静的メソッド

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

Notification.isSupported()

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

Notification.handleActivation(callback) Windows

Registers a callback to handle all notification activations. The callback is invoked whenever a notification is clicked, replied to, or has an action button pressed - regardless of whether the original Notification object is still in memory.

This method handles timing automatically:

  • If an activation already occurred before calling this method, the callback is invoked immediately with those details.
  • For all subsequent activations, the callback is invoked when they occur.

The callback remains registered until replaced by another call to handleActivation.

This provides a centralized way to handle notification interactions that works in all scenarios:

  • Cold start (app launched from notification click)
  • Notifications persisted in AC that have no in-memory representation after app re-start
  • Notification object was garbage collected
  • Notification object is still in memory (callback is invoked in addition to instance events)
const { Notification, app } = require('electron')

app.whenReady().then(() => {
// Register handler for all notification activations
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

Returns Promise<Notification[]> - Resolves with an array of Notification objects representing all delivered notifications still present in Notification Center.

Each returned Notification is a live object connected to the corresponding delivered notification. Interaction events (click, reply, action, close) will fire on these objects when the user interacts with the notification in Notification Center. This is useful after an app restart to re-attach event handlers to notifications from a previous session.

The returned notifications have their id, groupId, title, subtitle, and body properties populated from information available in the Notification Center. Other properties (e.g., actions, silent, icon) are not available from delivered notifications and will have default values.

[!NOTE] Like all macOS notification APIs, this method requires the application to be code-signed. In unsigned development builds, notifications are not delivered to Notification Center and this method will resolve with an empty array.

[!NOTE] Unlike notifications created with new Notification(), notifications returned by getHistory() will remain visible in Notification Center when the object is garbage collected. Calling show() on a restored notification will remove the original from Notification Center and post a new one with the same properties.

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

app.whenReady().then(async () => {
// Restore notifications from a previous session
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}`)
})
}
// Keep references so events continue to fire
})

Notification.remove(id) macOS

  • id (string | string[]) - The notification identifier(s) to remove. These correspond to the id values set in the Notification constructor.

Removes one or more delivered notifications from Notification Center by their identifier(s).

const { Notification } = require('electron')

// Remove a single notification
Notification.remove('my-notification-id')

// Remove multiple notifications
Notification.remove(['msg-1', 'msg-2', 'msg-3'])

Notification.removeAll() macOS

Removes all of the app's delivered notifications from Notification Center.

const { Notification } = require('electron')

Notification.removeAll()

Notification.removeGroup(groupId) macOS

  • groupId string - The group identifier of the notifications to remove. This corresponds to the groupId value set in the Notification constructor.

Removes all delivered notifications with the given groupId from Notification Center.

const { Notification } = require('electron')

// Remove all notifications in the 'chat-thread-1' group
Notification.removeGroup('chat-thread-1')

new Notification([options])

  • options Object (任意)
    • id string (optional) macOS Windows - A unique identifier for the notification. On macOS, maps to UNNotificationRequest's identifier property. On Windows, maps to the toast notification's Tag property. Defaults to a random UUID if not provided or if an empty string is passed. Use this identifier with Notification.remove() to remove specific delivered notifications, or with Notification.getHistory() to identify them.
    • groupId string (optional) macOS Windows - A string identifier used to visually group notifications together in Notification Center / Action Center. On macOS, maps to UNNotificationContent's threadIdentifier property. On Windows, maps to the toast notification's Group property. Use this identifier with Notification.removeGroup() to remove all notifications in a group.
    • groupTitle string (optional) Windows - A title for the notification group header. When both groupId and groupTitle are specified, Windows will display a header above the notification that groups related notifications together. Maps to the toast notification's header element.
    • title string (任意) - 通知ウィンドウの上部に表示される通知のタイトルです。
    • subtitle string (任意) macOS - タイトルの下に表示される、通知のサブタイトル。
    • body string (任意) - タイトルやサブタイトルの下に表示さる、通知の本文。
    • silent boolean (任意) - 通知を表示するときに OS が通知音を鳴らさないかどうか。
    • icon (string | NativeImage) (任意) - 通知に使用するアイコン。 文字列を渡す場合、ローカルのアイコンファイルへの有効なパスでなければなりません。
    • hasReply boolean (optional) macOS Windows - Whether or not to add an inline reply option to the notification.
    • timeoutType string (任意) Linux Windows - 通知の消失までの時間。 'default' か 'never' にできます。
    • replyPlaceholder string (optional) macOS Windows - The placeholder to write in the inline reply input field.
    • sound string (任意) macOS - 通知が表示されるときに再生される音声ファイルの名前。
    • urgency string (optional) Linux Windows - The urgency level of the notification. 'normal'、'critical'、'low' のいずれかにできます。
    • actions NotificationAction[] (optional) macOS Windows - Actions to add to the notification. NotificationAction ドキュメント内の有効なアクションと制限を読んで下さい。
    • closeButtonText string (任意) macOS - 通知を閉じるボタンのカスタムタイトル。 空の文字列の場合は、既定のローカライズされたテキストが使用されます。
    • toastXml string (任意) Windows - Windows 通知のカスタム記述は、上記のプロパティすべてを上書きします。 これは通知のデザインと動作の完全なカスタマイズを提供します。

[!NOTE] On Windows, urgency type 'critical' sorts the notification higher in Action Center (above default priority notifications), but does not prevent auto-dismissal. To prevent auto-dismissal, you should also set timeoutType to 'never'.

インスタンスイベント

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

info

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

イベント: '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 (optional) - The reason the notification was closed. This can be 'userCanceled', 'applicationHidden', or '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()
})

Event: '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()
})

Event: 'action' macOS Windows

戻り値:

  • details Event<>
    • actionIndex number - アクティベートされたアクションのインデックス.
    • selectionIndex number Windows - The index of the selected item, if one was chosen. -1 if none was chosen.
  • actionIndex number Deprecated
  • selectionIndex number Windows Deprecated
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()
})

Event: '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 が表示する前にこのメソッドを呼び出す必要があります。

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

On macOS, calling show() on a notification returned by Notification.getHistory() will remove the original notification from Notification Center and post a new one with the same properties.

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

A string property representing the unique identifier of the notification. This is set at construction time — either from the id option or as a generated UUID if none was provided.

notification.groupId macOS Windows Readonly

A string property representing the group identifier of the notification. Notifications with the same groupId will be visually grouped together in Notification Center (macOS) or Action Center (Windows).

notification.groupTitle Windows Readonly

A string property representing the title of the notification group header.

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 のドキュメントをご参照ください。