Notification
创建操作系统桌面通知
进程:主进程
如果您想从渲染器进程显示通知,您应该使用 Web 通知 API
类:Notification
创建操作系统桌面通知
进程:主进程
Notification 是一个 EventEmitter。
它使用 options 中设置的原生属性创建一个新的 Notification。
Electron 的内置类不能被用户代码继承。更多信息,请参阅常见问题解答。
静态方法
Notification 类具有以下静态方法
Notification.isSupported()
返回 boolean - 当前系统是否支持桌面通知
new Notification([options])
实例事件
使用 new Notification 创建的对象会发出以下事件
某些事件仅在特定操作系统上可用,并已相应标记。
事件:'show'
返回
eventEvent
当通知显示给用户时发出。请注意,此事件可能会多次触发,因为可以通过 show() 方法多次显示通知。
事件:'click'
返回
eventEvent
当用户点击通知时发出。
事件:'close'
返回
eventEvent
当通知被用户手动关闭时发出。
此事件不保证在通知关闭的所有情况下都发出。
在 Windows 上,close 事件可以通过三种方式发出:通过 notification.close() 以编程方式关闭、用户关闭通知,或通过系统超时。如果在初始 close 事件发出后通知仍保留在操作中心,调用 notification.close() 会将通知从操作中心移除,但 close 事件不会再次发出。
事件:'reply' macOS
返回
eventEventreplystring - 用户在内联回复字段中输入的字符串。
当用户点击具有 hasReply: true 的通知上的“回复”按钮时发出。
事件:'action' macOS
返回
eventEventindexnumber - 激活的操作的索引。
事件:'failed' Windows
返回
eventEventerrorstring - 在执行show()方法期间遇到的错误。
在创建和显示原生通知时遇到错误时发出。
实例方法
使用 new Notification() 构造函数创建的对象具有以下实例方法
notification.show()
立即向用户显示通知。与 Web 通知 API 不同,实例化 new Notification() 不会立即向用户显示。相反,您需要在操作系统显示通知之前调用此方法。
如果通知之前已显示过,此方法将关闭之前显示的通知,并创建一个具有相同属性的新通知。
notification.close()
关闭通知。
在 Windows 上,当通知在屏幕上可见时调用 notification.close() 将关闭通知并将其从操作中心移除。如果在通知不再可见后调用 notification.close(),调用 notification.close() 将尝试将其从操作中心移除。
实例属性
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
表示通知自定义 Toast XML 的 string 属性。
播放声音
在 macOS 上,您可以指定显示通知时要播放的声音名称。可以使用任何默认声音(位于“系统偏好设置”>“声音”下),以及自定义声音文件。请确保声音文件已复制到应用程序包中(例如,YourApp.app/Contents/Resources)或以下位置之一
~/Library/Sounds/Library/Sounds/Network/Library/Sounds/System/Library/Sounds
有关更多信息,请参阅 NSSound 文档。