Aller au contenu principal

Notifications

Chaque système d'exploitation dispose de son propre mécanisme pour afficher les notifications aux utilisateurs. Les API de notification d'Electron sont multi-plateforme, mais sont différentes pour chaque type de processus.

Si vous désrirez utiliser une API d'un processus de rendu à partir du processus principal ou vice versa, vous devez utiliser la communication inter-processus.

Utilisation​

Voici deux exemples montrant comment afficher les notifications pour chaque type de processus.

Affichage de notifications à partir du processus principal​

Main process notifications are displayed using Electron's Notification module. Les objets de notification créés à l'aide de ce module ne s'affichent qu'apès l'appel à leur méthode d'instance 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()

Voici un exemple complet que vous pouvez ouvrir avec 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()
}
})

Afficher les notifications dans le processus de rendu​

Les notifications peuvent être affichées directement à partir du processus de rendu avec l'API des notifications web.

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)

Voici un exemple complet que vous pouvez ouvrir avec 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 }

Considérations relatives aux plate-formes​

Le code et l’expérience utilisateur sur les différents systèmes d’exploitation sont semblables, mais il y a des différences.

Windows​

Pour les notifications sous Windows, votre application Electron a besoin d'un raccourci du Menu Démarrer avec un AppUserModelID et un ToastActivatorCLSID correspondant.

Electron tente d'automatiser le travail autour de l'AppUserModelID et ToastActivatorCLSID. Quand Electron est utilisé avec Squirrel.Windows (par ex. si vous utilisez electron-winstaller), les raccourcis seront automatiquement définis correctement.

En production, Electron détectera également si Squirrel a été utilisé et appellera automatiquement app.setAppUserModelId() avec la valeur correcte. During development, you may have to call app.setAppUserModelId() yourself.

Notifications en développement

Afin de démarrer rapidement pendant le développement avec les notifications , vous pouvez également ajouter node_modules\electron\dist\electron.exe au menu Démarrer. Naviguez vers le fichier dans l'explorateur, cliquez avec le bouton droit de la souris et Épinglez le au menu de démarrage. Ensuite, appelez app.setAppUserModelId(process.execPath) dans le processus principal pour voir les notifications.

Utilisation de notifications avancées​

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.

Requête de l'état des notification​

Pour détecter si vous êtes autorisé ou non à envoyer une notification, utilisez le module utilisateur windows-notification-state.

Ce module vous permet de déterminer à l’avance si oui ou non Windows lancera silencieusement le Ce module vous permet de déterminer à l’avance si oui ou non Windows affichera silencieusement le notification.

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.

Notez que les notifications sont limitées à 256 octets de taille et risque d’être tronquées si vous dépassez cette limite.

Requête de l'état des notification​

Pour détecter si vous êtes autorisé ou non à envoyer une notification, utilisez le module userland macos-notification-state.

Ce module vous permet de détecter à l’avance si la notification sera affichée ou non.

Linux​

Notifications are sent using libnotify, which can show notifications on any desktop environment that follows Desktop Notifications Specification, including Cinnamon, Enlightenment, Unity, GNOME, and KDE.