跳转到主内容

通知

创建OS(操作系统)桌面通知

Process: Main

[!NOTE] If you want to show notifications from a renderer process you should use the web Notifications 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

创建OS(操作系统)桌面通知

Process: Main

Notification 是一个 EventEmitter

通过 options 来设置的一个新的原生 Notification

[!WARNING] Electron's built-in classes cannot be subclassed in user code. For more information, see the 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(可选)- 通知标题,在通知窗口顶部显示。
    • subtitlestring (可选) 通知的副标题, 显示在标题下面。_ macOS _
    • body string (可选) - 通知的正文文本,将显示在标题或副标题下面。
    • silent boolean(可选)- 是否在显示通知时禁止操作系统发出通知提示音。
    • icon (string | NativeImage) (optional) - An icon to use in the notification. If a string is passed, it must be a valid path to a local icon file.
    • 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 - 自定义的窗口通知描述可取代上面所有属性。 提供完全自定义的设计和通知行为。

[!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

Some events are only available on specific operating systems and are labeled as such.

事件: 'show'

返回:

  • event Event

Emitted when the notification is shown to the user. 请注意,由于通知可以通过调用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事件可被以下三种情况触发:调用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<>
    • replystring-用户在内联答复字段中输入的字符串.
  • reply string Deprecated

当用户单击 hasReply: true 的通知上的 "Reply" 按钮时触发。

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()
})

实例方法

Objects created with the new Notification() constructor have the following instance methods:

notification.show()

立即向用户展示通知。 不像 Web Notification API, 实例化一个 new Notification() 并不会立即向用户展示它。 相反,您需要调用此方法让操作系统显示通知。

如果以前已显示通知, 则此方法将忽略以前显示的通知,并创建具有相同属性的新通知

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()

忽略这条通知

On Windows, calling notification.close() while the notification is visible on screen will dismiss the notification and remove it from the Action Center. If notification.close() is called after the notification is no longer visible on screen, calling notification.close() will try remove it from the Action Center.

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'

Default is 'low' - see NotifyUrgency for more information.

notification.timeoutType Linux Windows

string 属性代表通知的超时持续时间。 可以是 'default' 或 'never'.

如果 timeoutType 设置为 'never',则通知永远不会过期。 它将一直开放直到调用API或用户关闭为止。

notification.actions

A NotificationAction[] property representing the actions of the notification.

notification.toastXml Windows

string 通过windows的 toastXML 自定义通知

播放声音

在 macOS 上, 您可以指定在显示通知时要播放的声音的名称。 除了自定义声音文件之外, 还可以使用任何默认声音 (系统首选项 > 声音)。 请确保声音文件是在应用程序包(例如, YourApp.app/Contents/Resources) 内存在副本, 或者是下列位置之一:

  • ~/Library/Sounds
  • /Library/Sounds
  • /Network/Library/Sounds
  • /System/Library/Sounds

See the NSSound docs for more information.