Skip to main content

Notification

创建操作系统桌面通知

进程:主进程

🌐 Process: Main

note

如果你想从渲染进程显示通知,你应该使用 Web 通知 API

note

在 MacOS 上,通知使用 UNNotification API 作为其底层框架。 该 API 要求应用必须进行代码签名,以便通知能够显示。 未签名的二进制文件在调用通知时会触发 failed 事件。

类:Notification

🌐 Class: Notification

创建操作系统桌面通知

进程:主进程

🌐 Process: Main

Notification 是一个 事件触发器

它会创建一个新的 Notification,其本地属性由 options 设置。

🌐 It creates a new Notification with native properties as set by the options.

warning

Electron 内置的类不能在用户代码中被继承。 欲了解更多信息,请参见 常见问题

静态方法

🌐 Static Methods

Notification 类具有以下静态方法:

🌐 The Notification class has the following static methods:

Notification.isSupported()

返回 boolean - 当前系统是否支持桌面通知

🌐 Returns boolean - Whether or not desktop notifications are supported on the current system

Notification.handleActivation(callback) Windows

注册一个回调以处理所有通知激活。每当通知被点击、回复或按下操作按钮时,都会调用该回调——无论原始的 Notification 对象是否仍在内存中。

🌐 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:

  • 如果在调用此方法之前已经发生了激活,则回调会立即使用这些详细信息被调用。
  • 对于所有后续的激活,回调在它们发生时被调用。

回调将保持注册状态,直到被另一次对 handleActivation 的调用替换。

🌐 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:

  • 冷启动(从通知点击启动的应用)
  • 在应用重启后,AC 中仍然存在但内存中没有表示的通知
  • 通知对象已被垃圾回收
  • 通知对象仍在内存中(回调除了实例事件外还会被调用)
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

返回 Promise<Notification[]> - 解析为一个 Notification 对象数组,表示通知中心中仍然存在的所有已发送通知。

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

每个返回的 Notification 都是一个与相应已发送通知相关联的活动对象。当用户在通知中心与通知进行交互时,这些对象上将触发交互事件(clickreplyactionclose)。在应用重启后,这对于重新将事件处理程序附加到上一个会话的通知非常有用。

🌐 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.

返回的通知其 idgroupIdtitlesubtitlebody 属性会根据通知中心中可用的信息填充。其他属性(例如 actionssilenticon)无法从已发送的通知中获取,将具有默认值。

🌐 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

和所有 macOS 通知 API 一样,该方法要求应用必须进行代码签名。在未签名的开发版本中,通知不会发送到通知中心,并且该方法将返回一个空数组。

note

与使用 new Notification() 创建的通知不同,由 getHistory() 返回的通知在对象被垃圾回收时仍会在通知中心可见。在恢复的通知上调用 show() 将会从通知中心移除原始通知,并发布一个具有相同属性的新通知。

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

new Notification([options])

  • options 对象(可选)
    • id string (optional) macOS Windows - 通知的唯一标识符。在 macOS 上,映射到 UNNotificationRequestidentifier 属性。在 Windows 上,映射到 Toast 通知的 Tag 属性。如果未提供或传入空字符串,则默认为随机 UUID。可用于移除或更新之前发送的通知。
    • groupId string (optional) macOS Windows - 用于在通知中心/操作中心中将通知视觉上分组的字符串标识符。在 macOS 上,对应 UNNotificationContentthreadIdentifier 属性。在 Windows 上,对应 toast 通知的 Group 属性。
    • groupTitle string (optional) Windows - 通知组标题。当同时指定 groupIdgroupTitle 时,Windows 会在通知上方显示一个标题,将相关通知分组在一起。映射到 Toast 通知的 header 元素。
    • title string(optional)- 通知的标题,当通知显示时会显示在通知窗口的顶部。
    • subtitle string (optional) macOS - 通知的副标题,将显示在标题下方。
    • body string(optional)- 通知的正文内容,将显示在标题或副标题下方。
    • silent boolean(optional)- 在显示通知时是否抑制操作系统的通知噪音。
    • icon(字符串 | NativeImage)(可选))- 用于通知的图标。如果传递的是字符串,则必须是本地图标文件的有效路径。
    • hasReply boolean (optional) macOS Windows - 是否在通知中添加内联回复选项。
    • timeoutType string (optional) Linux Windows - 通知的超时时长。可以是“默认”或“从不”。
    • replyPlaceholder string (optional) macOS Windows - 在内联回复输入框中书写的占位符。
    • sound string (optional) macOS - 在显示通知时要播放的声音文件的名称。
    • urgency string (optional) Linux Windows - 通知的紧急程度。可以是“普通”、“关键”或“低”。
    • actions NotificationAction[] (optional) macOS Windows - 要添加到通知的操作。请阅读 NotificationAction 文档中可用的操作和限制。
    • closeButtonText string (optional) macOS - 警报关闭按钮的自定义标题。空字符串将使用默认的本地化文本。
    • toastXml string (optional) Windows - Windows 通知的自定义描述,覆盖上面所有属性。提供通知的设计和行为的完全自定义。
note

在 Windows 上,urgency 类型的“关键”会将通知在操作中心中排序得更高(高于默认优先级通知),但不会阻止自动消失。要防止自动消失,你还应该将 timeoutType 设置为“从不”。

实例事件

🌐 Instance Events

使用 new Notification 创建的对象会触发以下事件:

🌐 Objects created with new Notification emit the following events:

info

某些事件仅在特定操作系统上可用并如此标记。

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

Event: 'show'

返回:

🌐 Returns:

  • event 事件

当通知显示给用户时触发。请注意,此事件可能会被触发多次,因为通过 show() 方法通知可以显示多次。

🌐 Emitted when the notification is shown to the user. Note that this event can be fired multiple times as a notification can be shown multiple times through the show() method.

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

Event: 'click'

返回:

🌐 Returns:

  • event 事件

当用户单击通知时发出。

🌐 Emitted when the notification is clicked by the user.

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

Event: 'close'

返回:

🌐 Returns:

  • details 事件<>
    • reason Windows string(optional)- 通知被关闭的原因。这可以是“用户取消”、“应用隐藏”或“超时”。

当用户手动干预关闭通知时发出。

🌐 Emitted when the notification is closed by manual intervention from the user.

在通知被关闭的所有情况下,不保证会触发此事件。

🌐 This event is not guaranteed to be emitted in all cases where the notification is closed.

在 Windows 中,close 事件可以通过三种方式触发:使用 notification.close() 进行程序化关闭、用户关闭通知,或者系统超时。如果通知在初始 close 事件触发后仍在操作中心中,调用 notification.close() 将会从操作中心移除该通知,但 close 事件不会再次触发。

🌐 On Windows, the close event can be emitted in one of three ways: programmatic dismissal with notification.close(), by the user closing the notification, or via system timeout. If a notification is in the Action Center after the initial close event is emitted, a call to notification.close() will remove the notification from the action center but the close event will not be emitted again.

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

返回:

🌐 Returns:

  • details 事件<>
    • reply string - 用户输入到行内回复字段的字符串。
  • reply 字符串 已弃用

当用户点击带有 hasReply: true 的通知上的“回复”按钮时触发。

🌐 Emitted when the user clicks the "Reply" button on a notification with 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

返回:

🌐 Returns:

  • details 事件<>
    • actionIndex number - 被激活操作的索引。
    • selectionIndex number Windows - 所选项目的索引,如果有选择的话。没有选择则为 -1。
  • actionIndex 编号 已弃用
  • selectionIndex 号码 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()
})

Event: 'failed' Windows

返回:

🌐 Returns:

  • event 事件
  • error string - 在执行 show() 方法时遇到的错误。

创建和显示原生通知时遇到错误时发出。

🌐 Emitted when an error is encountered while creating and showing the native notification.

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

实例方法

🌐 Instance Methods

使用 new Notification() 构造函数创建的对象具有以下实例方法:

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

notification.show()

立即向用户显示通知。与网页通知 API 不同,实例化 new Notification() 不会立即向用户显示通知。相反,你需要调用此方法,操作系统才会显示通知。

🌐 Immediately shows the notification to the user. Unlike the web notification API, instantiating a new Notification() does not immediately show it to the user. Instead, you need to call this method before the OS will display it.

如果通知之前已经显示过,此方法将关闭之前显示的通知,并创建一个具有相同属性的新通知。

🌐 If the notification has been shown before, this method will dismiss the previously shown notification and create a new one with identical properties.

在 macOS 上,对 Notification.getHistory() 返回的通知调用 show() 将会从通知中心移除原来的通知,并发布一个具有相同属性的新通知。

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

驳回通知。

🌐 Dismisses the notification.

在 Windows 上,当通知在屏幕上可见时调用 notification.close() 会关闭该通知并将其从操作中心移除。如果在通知不再在屏幕上可见后调用 notification.close(),调用 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)
})

实例属性

🌐 Instance Properties

notification.id macOS Windows 只读

🌐 notification.id macOS Windows Readonly

string 属性表示通知的唯一标识符。该属性在构造时设置——要么来自 id 选项,要么如果未提供,则生成一个 UUID。

🌐 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 只读

🌐 notification.groupId macOS Windows Readonly

string 属性表示通知的组标识符。具有相同 groupId 的通知将在通知中心(macOS)或操作中心(Windows)中以视觉方式分组显示。

🌐 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 只读

🌐 notification.groupTitle Windows Readonly

一个 string 属性,表示通知组标题。

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

notification.title

string 属性,表示通知的标题。

🌐 A string property representing the title of the notification.

notification.subtitle

一个 string 属性,表示通知的副标题。

🌐 A string property representing the subtitle of the notification.

notification.body

一个 string 属性,表示通知的正文。

🌐 A string property representing the body of the notification.

notification.replyPlaceholder

一个 string 属性,表示通知的回复占位符。

🌐 A string property representing the reply placeholder of the notification.

notification.sound

string 属性,表示通知的声音。

🌐 A string property representing the sound of the notification.

notification.closeButtonText

string 属性表示通知的关闭按钮文本。

🌐 A string property representing the close button text of the notification.

notification.silent

boolean 属性,表示通知是否为静音。

🌐 A boolean property representing whether the notification is silent.

notification.hasReply

boolean 属性表示通知是否具有回复操作。

🌐 A boolean property representing whether the notification has a reply action.

notification.urgency Linux

string 属性表示通知的紧急程度。可以是“普通”、“紧急”或“低”。

🌐 A string property representing the urgency level of the notification. Can be 'normal', 'critical', or 'low'.

默认值为“低”-更多信息请参见 NotifyUrgency

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

notification.timeoutType Linux Windows

string 属性,表示通知的超时时长类型。可以是 'default' 或 'never'。

🌐 A string property representing the type of timeout duration for the notification. Can be 'default' or 'never'.

如果将 timeoutType 设置为“从不”,通知将永不过期。它会一直显示,直到调用 API 或用户将其关闭。

🌐 If timeoutType is set to 'never', the notification never expires. It stays open until closed by the calling API or the user.

notification.actions

一个 NotificationAction[] 属性,表示通知的操作。

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

notification.toastXml Windows

string 属性表示通知的自定义 Toast XML。

🌐 A string property representing the custom Toast XML of the notification.

播放声音

🌐 Playing Sounds

在 macOS 上,当显示通知时,你可以指定想要播放的声音名称。除了自定义声音文件外,任何默认声音(在“系统偏好设置 > 声音”下)都可以使用。确保该声音文件已复制到应用包中(例如 YourApp.app/Contents/Resources),或者放置在以下位置之一:

🌐 On macOS, you can specify the name of the sound you'd like to play when the notification is shown. Any of the default sounds (under System Preferences > Sound) can be used, in addition to custom sound files. Be sure that the sound file is copied under the app bundle (e.g., YourApp.app/Contents/Resources), or one of the following locations:

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

有关更多信息,请参阅 NSSound 文档。

🌐 See the NSSound docs for more information.