Notificações
Visão Geral
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.
Exemplo
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>
...and add the renderer.js
file:
- 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
Após iniciar o aplicativo Electron, você verá a notificação:
Além disso, se você clicar na notificação, o DOM atualizará para exibir 'Notificação clicada!".
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>
Após executar a aplicação em Electron, você deve ver a notificação do sistema:
Additional information
Enquanto o código e a experiência do usuário em sistemas operacionais sejam semelhantes, há algumas diferenças.
Windows
- On Windows 10, a shortcut to your app with an Application User Model ID must be installed to the Start Menu. This can be overkill during development, so adding
node_modules\electron\dist\electron.exe
to your Start Menu also does the trick. Navegue até o arquivo no Explorer, clique com o botão direito e "Fixar em Iniciar". You will then need to add the lineapp.setAppUserModelId(process.execPath)
to your main process to see notifications.
O Electron tenta automatizar o trabalho em torno do Application User Model ID. Quando o Electron é usado juntamente com o framework de instalação e atualização Squirrel, atalhos serão definidos automaticamente corretamente. Além disso, Electron irá detectar que o Squirrel foi usado e irá chamar automaticamente app.setAppUserModelId()
com o valor correto. Durante o desenvolvimento, você pode ter que chamar app.setAppUserModelId()
por si só.
Notificações Avançadas
Versões posteriores do Windows permitem notificações avançadas, com os modelos personalizados, imagens e outros elementos flexíveis. Para enviar essas notificações(tanto do processo principal, quanto do processo de renderização), use o módulo de userland electron-windows-notifications, que usa addons nativos Node parar enviar ToastNotification
e 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.
Modo Silêncio/ Apresentação
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
As notificações são simples no macOS, mas você deve estar ciente das diretrizes da Interface Humana da Apple sobre notificações.
Note que as notificações tem um limite de 256 bytes de tamanho e serão truncadas se você exceder esse limite.
Não perturbe / Estado de sessão
Para detectar se é ou não permitido enviar uma notificação, use o módulo da userland electron-notification-state.
Isso permitirá você detectar antes do tempo ou não a notificação que será exibida.
Linux
Notificações são enviadas usando libnotify
que podem mostrar notificações em qualquer ambiente de trabalho que segue as Especificação de Notificação em Desktop, incluindo Cinnamon, Enlightenment, Unity, GNOME, KDE.