通知¶
创建操作系统桌面通知
进程:主进程
[!NOTE] 如果你想在渲染进程中显示通知,应使用 Web Notifications API
[!NOTE] 在 macOS 上,通知使用 UNNotification API 作为其底层框架。 此 API 要求应用经过代码签名,通知才能显示。 未签名的二进制文件在调用通知时会触发
failed事件。
类:Notification¶
创建操作系统桌面通知
进程:主进程
Notification 是一个 EventEmitter。
它根据 options 中设置的属性创建一个新的 Notification。
[!WARNING] Electron 的内置类不能在用户代码中子类化。 更多信息,请参阅 常见问题。
静态方法¶
Notification 类具有以下静态方法:
Notification.isSupported()¶
返回 boolean - 当前系统是否支持桌面通知
Notification.handleActivation(callback) Windows¶
callbackFunctiondetailsActivationArguments - 通知激活的详细信息。
注册一个回调以处理所有通知激活。每当通知被点击、回复或按下操作按钮时,都会调用该回调——无论原始 Notification 对象是否仍在内存中。
此方法会自动处理时序:
- 如果在调用此方法之前已经发生激活,则立即使用相应详细信息调用回调。
- 对于后续所有激活,回调会在发生时被调用。
回调会保持注册状态,直到被另一次 handleActivation 调用替换。
这提供了一种集中处理通知交互的方式,适用于所有场景:
- 冷启动(应用从通知点击启动)
- 持久化在操作中心(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 对象数组解析,表示通知中心中仍然存在的所有已送达通知。
每个返回的 Notification 都是与相应已送达通知相连的实时对象。当用户在通知中心与通知交互时,这些对象会触发交互事件(click、reply、action、close)。这在应用重启后很有用,可将事件处理程序重新附加到上一个会话的通知。
返回的通知的 id、groupId、title、subtitle 和 body 属性会从通知中心中可用的信息填充。其他属性(例如 actions、silent、icon)无法从已送达通知中获取,并将具有默认值。
[!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
})
Notification.remove(id) macOS¶
id(string | string[]) - 要移除的通知标识符。这些对应于在Notification构造函数 中设置的id值。
通过其标识符从通知中心移除一个或多个已送达通知。
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¶
从通知中心移除应用的所有已送达通知。
Notification.removeGroup(groupId) macOS¶
groupIdstring - 要移除的通知的组标识符。这对应于在Notification构造函数 中设置的groupId值。
从通知中心移除所有具有给定 groupId 的已送达通知。
const { Notification } = require('electron')
// Remove all notifications in the 'chat-thread-1' group
Notification.removeGroup('chat-thread-1')
new Notification([options])¶
optionsObject (optional)idstring (optional) macOS Windows - 通知的唯一标识符。在 macOS 上,映射到UNNotificationRequest的identifier属性。在 Windows 上,映射到 toast 通知的Tag属性。如果未提供或传入空字符串,则默认为随机 UUID。使用此标识符配合Notification.remove()移除特定已送达通知,或配合Notification.getHistory()识别它们。groupIdstring (optional) macOS Windows - 用于在通知中心 / 操作中心中对通知进行视觉分组的字符串标识符。在 macOS 上,映射到UNNotificationContent的threadIdentifier属性。在 Windows 上,映射到 toast 通知的Group属性。使用此标识符配合Notification.removeGroup()移除组中的所有通知。groupTitlestring (optional) Windows - 通知组标题的标题。当同时指定groupId和groupTitle时,Windows 会在通知上方显示一个标题,将相关通知分组。映射到 toast 通知的header元素。titlestring (optional) - 通知的标题,显示时位于通知窗口顶部。subtitlestring (optional) macOS - 通知的副标题,显示在标题下方。bodystring (optional) - 通知的正文文本,显示在标题或副标题下方。silentboolean (optional) - 显示通知时是否抑制操作系统通知声音。icon(string | NativeImage) (optional) - 通知中使用的图标。如果传入字符串,则必须是本地图标文件的有效路径。hasReplyboolean (optional) macOS Windows - 是否向通知添加内联回复选项。timeoutTypestring (optional) Linux Windows - 通知的超时时长。可以是 'default' 或 'never'。replyPlaceholderstring (optional) macOS Windows - 内联回复输入框中要写入的占位符。soundstring (optional) macOS - 显示通知时要播放的声音文件名称。urgencystring (optional) Linux Windows - 通知的紧急程度级别。可以是 'normal'、'critical' 或 'low'。actionsNotificationAction[] (optional) macOS Windows - 要添加到通知的操作。请阅读NotificationAction文档中可用的操作和限制。closeButtonTextstring (optional) macOS - 警报关闭按钮的自定义标题。空字符串将导致使用默认本地化文本。toastXmlstring (optional) Windows - Windows 上通知的自定义描述,覆盖上述所有属性。提供对通知设计和行为的完全自定义。
[!NOTE] 在 Windows 上,
urgency类型 'critical' 会将通知在操作中心中排序更高(高于默认优先级通知),但不会阻止自动消失。若要阻止自动消失,还应将timeoutType设置为 'never'。
实例事件¶
使用 new Notification 创建的对象会发出以下事件:
:::info
某些事件仅在特定操作系统上可用,并会相应标注。
:::
事件:'show'¶
返回:
eventEvent
当通知显示给用户时发出。注意,此事件可能多次触发,因为通知可以通过 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'¶
返回:
eventEvent
当用户点击通知时发出。
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'¶
返回:
detailsEvent\<>reasonWindows string(可选) - 通知被关闭的原因。可能是 'userCanceled'、'applicationHidden' 或 '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()
})
事件:'reply' macOS Windows¶
返回:
detailsEvent\<>replystring - 用户在行内回复字段中输入的字符串。replystring 已弃用
当用户点击带有 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' macOS Windows¶
返回:
detailsEvent\<>actionIndexnumber - 被激活的操作的索引。selectionIndexnumber Windows - 如果选择了某一项,则为所选项目的索引;如果未选择任何项,则为 -1。actionIndexnumber 已弃用selectionIndexnumber 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¶
返回:
eventEventerrorstring - 在执行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()¶
立即向用户显示通知。与 Web 通知 API 不同,实例化 new Notification() 不会立即向用户显示它。相反,你需要调用此方法,操作系统才会显示它。
如果通知之前已经显示过,此方法将关闭之前显示的通知,并创建一个具有相同属性的新通知。
在 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 只读¶
一个 string 属性,表示通知的唯一标识符。这在构造时设置——来自 id 选项,或者在未提供时生成的 UUID。
notification.groupId macOS Windows 只读¶
一个 string 属性,表示通知的组标识符。具有相同 groupId 的通知将在 Notification Center(macOS)或 Action Center(Windows)中视觉上分组显示。
notification.groupTitle Windows 只读¶
一个 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)下,或以下位置之一:
~/Library/Sounds/Library/Sounds/Network/Library/Sounds/System/Library/Sounds
有关更多信息,请参阅 NSSound 文档。
本页原文 Markdown:在 AtomGit 查看·内容源自开源项目 el/electron