Notificações
#
Visão GeralAll 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 processStarting 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:
- index.html
- main.js
- renderer.js
<!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 { 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() }})
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 processStarting with a working application from the Quick Start Guide, update the main.js
file with the following lines:
- index.html
- main.js
<!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>
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() }})
Após executar a aplicação em Electron, você deve ver a notificação do sistema:
#
Additional informationEnquanto 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. - No Windows 8.1 e Windows 8, um atalho para o seu aplicativo, com um, Application User Model ID deve ser instalado na tela inicial. No entanto, ele não precisa ser fixado na a tela iniciar.
- No Windows 7, notificações funcionam através de uma implementação personalizada que visualmente se assemelha aos sistemas mais novos.
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ó.
Além disso, no Windows 8, o comprimento máximo para o corpo da notificação é de 250 caracteres, o time do Windows recomenda que a notificações tenha 200 caracteres. Dito isto, essa limitação foi removida no Windows 10, mas a equipe do Windows pede que os desenvolvedores seja razoável. Tentativa de enviar gigantescas quantidades de texto pela API (milhares de caracteres) pode resultar em instabilidade.
#
Notificações AvançadasVersõ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çãoTo 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.
#
macOSAs 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ãoPara 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.
#
LinuxNotificaçõ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.