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