Notificaciones
Descripción general
All three operating systems provide means for applications to send notifications to the user. The technique of showing notifications is different for the Main and Renderer processes.
For the Renderer process, Electron conveniently allows developers to send notifications with the HTML5 Notification API, using the currently running operating system's native notification APIs to display it.
To show notifications in the Main process, you need to use the Notification module.
Ejemplo
Show notifications in the Renderer process
Starting with a working application from the Quick Start Guide, add the following line to the index.html
file before the closing </body>
tag:
<script src="renderer.js"></script>
...y agregar el archivo renderer.js
:
- main.js
- index.html
- renderer.js
const { app, BrowserWindow } = require('electron')
function createWindow () {
const win = new BrowserWindow({
width: 800,
height: 600
})
win.loadFile('index.html')
}
app.whenReady().then(createWindow)
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') {
app.quit()
}
})
app.on('activate', () => {
if (BrowserWindow.getAllWindows().length === 0) {
createWindow()
}
})
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Hello World!</title>
<meta http-equiv="Content-Security-Policy" content="script-src 'self' 'unsafe-inline';" />
</head>
<body>
<h1>Hello World!</h1>
<p>After launching this application, you should see the system notification.</p>
<p id="output">Click it to see the effect in this interface.</p>
<script src="renderer.js"></script>
</body>
</html>
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 = () => document.getElementById("output").innerText = CLICK_MESSAGE
After launching the Electron application, you should see the notification:
Additionally, if you click on the notification, the DOM will update to show "Notification clicked!".
Show notifications in the Main process
Starting with a working application from the Quick Start Guide, update the main.js
file with the following lines:
- main.js
- index.html
const { app, BrowserWindow, Notification } = require('electron')
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()
}
})
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Hello World!</title>
<meta http-equiv="Content-Security-Policy" content="script-src 'self' 'unsafe-inline';" />
</head>
<body>
<h1>Hello World!</h1>
<p>After launching this application, you should see the system notification.</p>
</body>
</html>
After launching the Electron application, you should see the system notification:
Información adicional
Si bien el código y la experiencia del usuario en los sistemas operativos son similares, existen diferencias sutiles.
Windows
- En Windows 10, se debe instalar un acceso directo a tu app en el menú de inicio con la ID del modelo de usuario de la aplicación. This can be overkill during development, so adding
node_modules\electron\dist\electron.exe
to your Start Menu also does the trick. Navigate to the file in Explorer, right-click and 'Pin to Start Menu'. You will then need to add the lineapp.setAppUserModelId(process.execPath)
to your main process to see notifications.
Electron intenta automatizar el trabajo en torno de la Application User Model ID. Cuando Electron es usado junto con el framework de instalación y actualización Squirrel shortcuts will automatically be set correctly. Además, Electron detectará que Squirrel fue usada y automáticamente llamará a app.setAppUserModelId()
con el valor correcto. Durante el desarrollo, puede tener que llamar por ti mismo a app.setAppUserModelId()
.
Notificaciones Avanzadas
Las versiones posteriores de Windows permiten notificaciones avanzadas, con plantillas personalizadas, imágenes y otros elementos flexibles. Para enviar esas notificaciones (ya sea desde el proceso principal o desde el procesador), use el módulo de usuario electron-windows-notificaciones, que usa complementos de nodo nativos para enviar ToastNotification
y objetos TileNotification
.
While notifications including buttons work with electron-windows-notifications
, handling replies requires the use of electron-windows-interactive-notifications
, which helps with registering the required COM components and calling your Electron app with the entered user data.
Horas Silenciosas / Modo de Presentación
To detect whether or not you're allowed to send a notification, use the userland module electron-notification-state.
This allows you to determine ahead of time whether or not Windows will silently throw the notification away.
macOS
Las notificaciones son directas en macOS, pero usted debe ser conciente de Apple's Human Interface guidelines regarding notifications.
Tenga en cuenta que las notificaciones están limitadas a 256 bytes de tamaño y se truncarán si supera ese límite.
No molestar / Estado de Sesión
Para detectar si se le permite o no enviar una notificación, use el módulo de usuario electron-notification-state.
Esto le permitirá detectar con anticipación si la notificación se mostrará o no.
Linux
Las notificaciones se envían utilizando libnotify
que puede mostrar notificaciones en cualquier entorno de escritorio que siga la Especificación de Notificaciones de Escritorio, incluidos Cinnamon, Enlightenment, Unity, GNOME, KDE.