跳转到主内容

通知(Notifications)

每个操作系统都有自己的机制向用户显示通知。 Electron的通知 API 是跨平台的,但对每个 进程 类型来说是不同的。

如果您想要在主进程中使用渲染进程 API,或者要在渲染进程中使用主进程 API,请考虑使用进程间通信。

用法​

下面是两个关于如何显示每个 进程 类型的通知的示例。

在主进程中显示通知​

主进程通知使用 Electron 的通知模块显示。使用此模块创建的通知对象不会立刻显示,除非调用他们的 show() 实例 方法。

Main Process
const { Notification } = require('electron')

const NOTIFICATION_TITLE = 'Basic Notification'
const NOTIFICATION_BODY = 'Notification from the Main process'

new Notification({
title: NOTIFICATION_TITLE,
body: NOTIFICATION_BODY
}).show()

下面是您可以使用 Electron Fiddle 打开的完整示例:

const { app, BrowserWindow, Notification } = require('electron/main')

function createWindow () {
const win = new BrowserWindow({
width: 800,
height: 600
})

win.loadFile('index.html')
}

const NOTIFICATION_TITLE = 'Basic Notification'
const NOTIFICATION_BODY = 'Notification from the Main process'

function showNotification () {
new Notification({ title: NOTIFICATION_TITLE, body: NOTIFICATION_BODY }).show()
}

app.whenReady().then(createWindow).then(showNotification)

app.on('window-all-closed', () => {
if (process.platform !== 'darwin') {
app.quit()
}
})

app.on('activate', () => {
if (BrowserWindow.getAllWindows().length === 0) {
createWindow()
}
})

在渲染进程中显示通知​

通知可以直接在渲染进程中使用 Web Notifications API 显示。

Renderer Process
const NOTIFICATION_TITLE = 'Title'
const NOTIFICATION_BODY = 'Notification from the Renderer process. Click to log to console.'
const CLICK_MESSAGE = 'Notification clicked'

new Notification(NOTIFICATION_TITLE, { body: NOTIFICATION_BODY }).onclick = () => console.log(CLICK_MESSAGE)

下面是您可以使用 Electron Fiddle 打开的完整示例:

const NOTIFICATION_TITLE = 'Title'
const NOTIFICATION_BODY = 'Notification from the Renderer process. Click to log to console.'
const CLICK_MESSAGE = 'Notification clicked!'

new window.Notification(NOTIFICATION_TITLE, { body: NOTIFICATION_BODY })
.onclick = () => { document.getElementById('output').innerText = CLICK_MESSAGE }

不同平台注意事项​

虽然操作系统的代码和用户体验相似,但依然存在微妙的差异。

Windows​

对于Windows上的通知 您的 Electron 应用需要有一个带有 AppUserModelID 和对应的 ToastActivatorCLSID 的开始菜单快捷方式。

Electron 尝试使AppUserModelID 和 ToastActivatorCLSID的工作自动化。 Electron在和安装和更新框架 Squirrel 一起使用的时候,Windows (例如你正在使用electron-winstaller)快捷方式将被自动正确的配置好。

在生产环境中,Electron 会自动检测 Squirrel 的存在,并且使用正确的值来自动调用app.setAppUserModelId()。在开发环境中, 你可能需要自己调用 app.setAppUserModelld() 。

开发环境中显示通知

为了快速实现开发模式下显示通知,因为将 node_modules\electron\dist\electron.exe 添加到您的开始菜单也可以解决问题。导航到资源管理器中的文件,右键单击并选择 “固定到开始菜单”。然后,在主进程中调用 app.setAppUserModelId(process.execPath) 以查看通知。

使用高级通知​

Windows allows for advanced notifications with custom templates, images, inputs, and action buttons.

To send advanced notifications from the main process on Windows, use the toastXml option of the Notification constructor. This property accepts an XML string conforming to the Microsoft Toast XML Schema and supersedes other notification options.

Main Process
const { Notification } = require('electron')

const xml = `
<toast>
<visual>
<binding template="ToastGeneric">
<text>Notification Title</text>
<text>Notification body text</text>
</binding>
</visual>
<actions>
<action content="Confirm" arguments="action=confirm" />
<action content="Dismiss" arguments="action=dismiss" />
</actions>
</toast>`

const notification = new Notification({ toastXml: xml })
notification.show()

Important considerations when using Toast XML on Windows:

  • AppUserModelID: You must call app.setAppUserModelId() before showing notifications. Windows uses this ID to associate toast notifications with your application in the notification center.
  • Image paths: When including local images in <image src="..." />, paths must be absolute and formatted as file:/// URLs (for example, using url.pathToFileURL(imagePath).toString()).
  • XML escaping: Dynamic strings placed inside XML elements or attributes must be XML-escaped (&amp;, &lt;, &gt;, &quot;, &apos;) to prevent XML parsing failures.
  • Error handling: If the XML string is malformed or invalid according to the Windows toast schema, the notification will not appear and the failed event will be emitted on the Notification instance.
  • Handling action buttons: Action buttons specify an arguments attribute. When clicked, Electron emits the action event with the action index. For deep-linking or custom protocol activation, specify activationType="protocol" on the <action> element.

查询通知状态​

要检测是否允许发送通知,请使用用户空间的 windows-notification-state 模块。

该模块允许你事先确定 Windows 是否会静默丢弃通知。

macOS​

For notifications on macOS, your application will need to be code-signed in order for notification events to emit correctly. This requirement stems from the underlying UNNotification API provided by Apple. Unsigned binaries will emit a failed event when notification APIs are called.

Additionally, you should be aware of Apple's Human Interface guidelines regarding notifications.

请注意,通知的大小限制为256个字节,如果超过该限制,则会被截断。

查询通知状态​

要检测是否允许发送通知,可以使用用户空间的macos-notification-state模块。

该模块允许你事先确定通知是否会被显示。

Linux​

在 Linux 上,通知是使用 libnotify 发送的,它可以在遵循桌面通知规范的任何桌面环境上显示通知,包括 Cinnamon、Enlightenment、Unity、GNOME 和 KDE。