00
:
00
:
00
:
00
Corso SEO AI - Usa SEOEMAIL al checkout per il 30% di sconto

Notifiche Native

Electron supporta le notifiche native del sistema operativo, permettendo alla tua applicazione di inviare notifiche anche quando non è in primo piano.

Notifica Base

// main.js
const { Notification } = require('electron');

function showNotification(title, body) {
  const notification = new Notification({
    title: title,
    body: body,
  });

  notification.show();
}

// Uso
showNotification('Download completato', 'Il file è stato scaricato con successo.');

Opzioni delle Notifiche

const notification = new Notification({
  title: 'Nuovo messaggio',
  subtitle: 'Da Mario Rossi',          // Solo macOS
  body: 'Ciao, come stai?',
  icon: path.join(__dirname, 'assets', 'icon.png'),
  silent: false,                         // Riproduci suono
  urgency: 'normal',                    // 'low', 'normal', 'critical' (Linux)
  timeoutType: 'default',               // 'default' o 'never'
  hasReply: true,                        // Mostra campo di risposta (macOS)
  replyPlaceholder: 'Scrivi una risposta...',  // Placeholder (macOS)
  closeButtonText: 'Chiudi',            // Testo bottone chiudi (macOS)
});

notification.show();

Gestire gli Eventi

const notification = new Notification({
  title: 'Aggiornamento disponibile',
  body: 'Clicca per installare la versione 2.0',
});

// L'utente ha cliccato sulla notifica
notification.on('click', () => {
  mainWindow.show();
  mainWindow.focus();
  mainWindow.webContents.send('notification:clicked', 'update');
});

// La notifica è stata chiusa
notification.on('close', () => {
  console.log('Notifica chiusa');
});

// L'utente ha risposto (macOS, con hasReply: true)
notification.on('reply', (_event, reply) => {
  console.log('Risposta:', reply);
});

// L'utente ha cliccato su un'azione
notification.on('action', (_event, index) => {
  console.log('Azione selezionata:', index);
});

notification.show();

Notifiche con Azioni (macOS)

const notification = new Notification({
  title: 'Promemoria',
  body: 'Riunione tra 5 minuti',
  actions: [
    { type: 'button', text: 'Posticipa' },
    { type: 'button', text: 'Ignora' },
  ],
});

notification.on('action', (_event, index) => {
  if (index === 0) {
    // Posticipa
    setTimeout(() => showReminder(), 5 * 60 * 1000);
  }
  // index === 1: Ignora
});

notification.show();

Verificare il Supporto

if (Notification.isSupported()) {
  // Le notifiche sono supportate
  new Notification({ title: 'Test', body: 'Funziona!' }).show();
} else {
  console.log('Notifiche non supportate su questa piattaforma');
}

Integrazione con IPC

// main.js
ipcMain.handle('notification:show', (_event, options) => {
  if (!Notification.isSupported()) return false;

  const notification = new Notification({
    title: options.title,
    body: options.body,
    icon: options.icon ? path.join(__dirname, options.icon) : undefined,
  });

  notification.on('click', () => {
    const win = BrowserWindow.fromWebContents(_event.sender);
    if (win) {
      win.show();
      win.focus();
    }
    _event.sender.send('notification:clicked', options.id);
  });

  notification.show();
  return true;
});
// preload.js
contextBridge.exposeInMainWorld('notifications', {
  show: (options) => ipcRenderer.invoke('notification:show', options),
  onClicked: (callback) => {
    ipcRenderer.on('notification:clicked', (_event, id) => callback(id));
  },
});
// renderer.js
async function notifyUser(title, body) {
  await window.notifications.show({ title, body, id: Date.now() });
}

window.notifications.onClicked((id) => {
  console.log('Notifica cliccata:', id);
});

Notifiche dal Renderer (Web API)

Puoi anche usare la Web Notification API standard nel renderer:

// renderer.js
if ('Notification' in window) {
  new window.Notification('Titolo', {
    body: 'Corpo della notifica',
    icon: './assets/icon.png',
  });
}

La Web Notification API è più semplice ma offre meno controllo rispetto al modulo Notification del Main Process.

Note per Piattaforma

  • Windows: Le notifiche richiedono un AppUserModelID per le app non installate. Electron lo gestisce automaticamente per le app distribuite con installer
  • macOS: Le notifiche supportano azioni, risposte e sottotitoli
  • Linux: Le notifiche dipendono dal desktop environment (GNOME, KDE, etc.)